Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise foreach expression in one line

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;
like image 667
Frank Avatar asked Feb 20 '09 16:02

Frank


3 Answers

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).

like image 152
Chris Lutz Avatar answered Sep 23 '22 07:09

Chris Lutz


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.

like image 28
Adam Bellaire Avatar answered Sep 24 '22 07:09

Adam Bellaire


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.

like image 40
Chad Birch Avatar answered Sep 22 '22 07:09

Chad Birch