3 ms·
Yea, my $file_handle = open(file.txt) my $text; while (read $file_handle, $buff, 1024) { $text = $buff } read returns the number of characters read (0 when
by joslin01 15y ago
Yea,
my $file_handle = open(file.txt)
my $text;
while (read $file_handle, $buff, 1024) { $text = $buff }
read returns the number of characters read (0 when it's finished which will end the loop). I don't know of any generic "read" function, so it's up to you to define how many characters at a time and give the $buffer scalar to read into. it's just a different way of doing things
norkakn is a better resource than this comment
- tocomment 15y agoI ended up going with this one for better or worse. I'm afraid I still don't quite understand it: my $text = do { local( @ARGV, $/ ) = $file ; <> } ;
- mdda 15y agoThe local $/ is the trick : It reset the line-end character to 'undef', which makes the <> line-slurp the whole file at once.
- abuzzooz 15y agoIf you don't understand it, why use it? Is it that important for you to do this in one line of (relatively obscured) code, than in 2-3 lines of readable code? For the record, the do() block defines @ARGV (which normally holds the command-line arguments) to contain the value of the $file (presumably a file name), and sets $/ (which is the input record separator) to an undefined value. In Perl, <> is synonymous to <STDIN> which makes it read from stdin. Since @ARGV now contains a file name, Perl will open this file for reading. Since $/ is undefined, Perl will enter in "slurp" mode, and will gobble up the whole file in one shot. Since this is the last statement in the do() block, it will be returned as its value, and stored in $text. Lots of Perl magic happening here. I advise you against using such shortcuts.
- lawn 15y agomy $txt = do { local $/ = <$file>; }; or my $txt = do { local $/; <$file>; }; are as I know the preferred ways to do it. As a previous comment explained, $/ is the record separator and when you localize it it's value is set to undef. Which means we read the whole filehandle (the second part). As a do block evaluates to the value of the last expression, the contents of the file is the result of the whole expression. If you're serious about Perl I recommend Modern Perl which is a 250 page really good introduction for the language, intended for programmers.
- sciurus 15y agoAgreed, the trick with a local ARGV and the null filehandle is too clever. Don't copy code you don't understand! I think opening the file is much clearer. open( my $fh, '<', $file ) or die "cannot open $file\n"; my $text = do { local( $/ ) ; <$fh> } ; http://perldoc.perl.org/perlopentut.html http://perldoc.perl.org/functions/do.html http://perldoc.perl.org/functions/local.html http://perldoc.perl.org/perlop.html#I%2fO-Operators