🌐
Videos Blog About Series πŸ—ΊοΈ
❓
πŸ”‘

How I learned to love postfix for in perl πŸ”—
1722982036  

🏷️ blog 🏷️ perl
Suppose you do a common thing like a mapping into a hash but decide to filter the input first:
shit.pl
my %hash = map {
    "here" => $_
} grep {
    -d $_
} qw{a b c d .};
This claims there is a syntax eror on line 6 where the grep starts. This is a clear violation of the principle of least-astonishment as both the map and grep work by themselves when not chained. We can fix this by assigning $_ like so:
fixed.pl
my %hash = map {
    my $subj = $_;
    "here" => $subj
} grep {
    my $subj = $_;
    -d $subj
} qw{a b c d .};

Now we get what we expect, which is no syntax error. This offends the inveterate golfer in me, but it is in many critic rules for a reason. In particular when nested lexical scope inside of the map/grep body is a problem, which is not the case here.

But never fear, there is a superior construct to map in all cases...postfix for!

oxyclean.pl
my %hash = "here" => $_ for grep { -d $_ } qw{a b c .};
No syntax errors and it's a oneliner. It's also faster due to not assigning a lexical scope.
25 most recent posts older than 1722982036
Size:
Jump to:
POTZREBIE
© 2020-2023 Troglodyne LLC