I have the following code but can it be done in one statement?
open FILE, $file;
while (<FILE>) { $filestr .= $_; }
I have the following code but can it be done in one statement?
open FILE, $file;
while (<FILE>) { $filestr .= $_; }
open FILE, $file; while (<FILE>) { $filestr .= $_; }
However, the presence of a newline is the last thing that would worry me about that snippet. I'd be more worried about the following:
open
,open
,use strict;
, and
open(my $fh, '<', $qfn)
or die("Can't open \"$qfn\": $!\n");
my $file; { local $/; $file = <$fh>; }
$ perldoc perlvar # /slurp<enter><copy example code><paste>
$ perl -E '
my $file = "test.txt";
my $content = "";
open my $fh, "<", $file or die $!;
{
local $/;
$content = <$fh>;
}
close $fh;
print $content;'
It's never going to be one statement. But anything can be "one line of code" in perl.
So… we're good right? You meant no looping didn't you.
Other stuff to consider:
open my FILE, '<', $file or die $!;
my @filestrs = <FILE>;
Or after cpanm File::Map
:
use File::Map qw(map_file);
map_file my $filestr, $file;
Similarly with Path::Tiny
:
use Path::Tiny;
my $filestr = path($file)->slurp; # or ->slurp_utf8;
Sort of one line:
my $filestr = do { local(@ARGV, $/) = $file; <> };
Fewer statements still:
open(my $fh, '<', $file);
read($fh, $filestr, -s $fh);
I would interpret your question to be:
How can the two statements be written as a single statement without using additional modules or subroutines.
Perl does not prevent you from shooting yourself in the foot, so if you consider semicolon to be the statement separator, the following could be considered as one statement:
open (FILE, $file) and do {$filestr .= $_ while (<FILE>)};
although there is an implicit semicolon at the end of the do
block, and this construction should never be used in real code since it prevents checking for open
errors the usual way:
open (FILE, $file) or die "Could not open file '$file': $!";