do {}
construct does not get much love in most of the code I see. Besides do {} while
loops, it is very useful for combining steps and limiting the scope of variables:my $contents = do {The snippet above keeps the change to
local $/;
open my $fh, "<", $filename
or die "could not open $filename: $!";
<$fh>;
};
$/
and the $fh
variable local to the section that needs it.
Yeah, I really like that.
ReplyDeleteSomething I often do (well, over several lines) is
my @file = do { use autodie; opendir my $dh, $directory; readdir $dh };
which limits the scope of the directory handle so I don’t need to close it, and segregates the “slurp directory contents” piece of the code into one block.
I often use this for slurping:
ReplyDeletemy $contents = do { local (@ARGV, $/) = "filename"; <> };
Needs more error checking of course, but for one-off scripts its great,