5 ms·
This is actually really simple in perl. The idiomatic way to do it would be: open(my $fh, "<", "file.txt") or die "wft?" my @lines = <$fh>; lines is now a
by shanemhansen 15y ago
This is actually really simple in perl. The idiomatic way to do it would be:
open(my $fh, "<", "file.txt") or die "wft?"
my @lines = <$fh>;
lines is now an array of lines, you can join them into a single string if you want.
- mapgrep 15y agoSlightly more idiomatic would be with a useful die (and a semicolon terminating the first line): open(my $fh, "<", "file.txt") or die "Error reading file: $!"; my @lines = <$fh>; To slurp into a string rather than an array of lines: open(my $fh, "<", "file.txt") or die "Error reading file: $!"; my $s = join('',<$fh>);
- ajross 15y agoOr just: my $data = `cat $file`; Some folks dislike the useful use of cat, but anyone who's ever read a shell script will recognize the idiom. And it's a trivial one-liner much simpler still than the python code .
- pdehaan 15y agoThis isn't exactly idiomatic Perl and fails completely in environments that don't have cat (Windows). For one-time uses there's not a problem. However, if you find yourself writing what amount to shell scripts in Perl, you might be better off just writing shell scripts.
- ajross 15y agoExcuse me? Who are you to determine what is and isn't "idiomatic"? And that you would try this kind of thing about perl of all languages is just shocking. What's saddest is that it's the lack of this kind of absurdist pursuit of robustness and purity is one of the things that has always best defined the perl community. Broadly, your argument seems to be that spawning processes in the external environment[1] (which, admittedly, is inherently nonportable) is a Bad Thing in perl, and that we shouldn't do it. When I rephrase it like that, does it sound as poo-flinging crazy to you as it does to me? [1] Let's be honest: a working "cat" is pretty much the single most portable thing you can put between the backticks. If you won't allow this, what will you permit?
- pdehaan 15y agoFirst off, apologies if I was coming off as rude, I wasn't trying to be. My point was more that slurping a file without spawning another process is already quite easy in perl. That method of slurping contradicts common patterns like "while (<$fh>)". I'm not saying it's strictly wrong or even bad, just not necassarily the best option.