In Perl, one can often avoid using control blocks, like this:
print "$_\n" foreach(@files);
instead of:
foreach(@files){
print "$_\n";
}
How does this syntax work in the following, more complex case:
die("Not a file: $_") unless -f $_ foreach(@files);
It gives me a syntax error. I'm not trying to write obfuscated code, it's just an unimportant part in the program, and so I want to express it as concisely as possible.
SUMMARIZED ANSWERS:
I can accept only one answer as the accepted answer, but I like the following ones from Chris and Jon best.
This one uses foreach
as I intended, but without the syntax error
:
-f or die "Not a file: $_" foreach @files;
And the following one is at least as good. I like that die
is at the beginning of the statement because that's what the reader's attention should be directed toward:
die("Not a file: $_") for grep {!-f} @files;
Just to be Perlish (TMTOWTDI) you can use logic short-circuiting:
-f or die "Not a file: $_" foreach @files;
Tested on OS X and works.
As a side note, -f or die
looks like a lot of common open() or die
constructs I see in Perl, and still (I think) shows the intention of the line (to die
under certain conditions).
You could either use @Brent.Longborough's answer, or if you really want postfix, do:
do { die("Not a file: $_") unless -f $_ } foreach(@files);
However, I agree with the others, just because this is "an unimportant part" doesn't mean that concise is better. Readability counts.
Well, you may not be intending to write obfuscated code, but I'd say that you're certainly trying to.
Would two lines (or even a block on one line, like Brent.Longborough suggests) instead of one be so bad? Honestly, this is the reason I generally hate trying to debug/edit other peoples' perl code, a large number of people that write in perl seem to be obsessed with doing almost everything in the most "clever" way possible, instead of doing it in a way that's easy to understand for someone else reading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With