in reply to Re^2: Need help figuring out how to order/eval the numbers
in thread Need help figuring out how to order/eval the numbers
Hello again perlynewby,
It seems that, between aaron_baugher’s excellent replies and your own further reading, you already have answers to most of your questions. I will just comment on this part of my code:
my $fh = defined $hash{$ita}[0] && defined $hash{$ita}[1] ? $out : $out1; print $fh "$ita => ", join(',', map { $_ // () } @{ $hash{$ita} }), "\n";
The ... ? ... : ... construct is the conditional, or ternary, operator, which is documented here. I use it to select which of two filehandles will be written to by the following print statement. This is an example of applying the DRY (“don’t repeat yourself”) principle by changing the original two parallel print statements into a single statement. The advantage here is that if the statement is later changed (see below!), there is no danger of updating one statement and overlooking the other in the process.
The expression { $_ // () } uses the Logical Defined-Or operator to select the empty parentheses — () — only if the current value ($_) is undefined. Empty parentheses are used because they represent an empty list, and interpolating an empty list into a second list has no effect on that second list. Any other value here — e.g. undef, "" (the empty string), [] (which is a reference to an empty anonymous array) — would add something unwanted to the second list, because in each case the value is a scalar which is added as a new list element. The following should make this a little clearer:
17:42 >perl -MData::Dump -wE "my @c = qw(a e i o u); @c = map { $_ eq +'i' ? undef : $_ } @c; dd \@c;" ["a", "e", undef, "o", "u"] 17:44 >perl -MData::Dump -wE "my @c = qw(a e i o u); @c = map { $_ eq +'i' ? () : $_ } @c; dd \@c;" ["a", "e", "o", "u"] 17:44 >
map...nice function, I'm geeking out on map right now.
Yor’re right! Unfortunately, map was the wrong function to use here. :-( I should have used grep:
print $fh "$ita => ", join(',', grep { defined } @{ $hash{$ita} }), "\n";
— much more straightforward. D’oh!
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Need help figuring out how to order/eval the numbers
by perlynewby (Scribe) on Jun 23, 2015 at 23:00 UTC | |
|
Re^4: Need help figuring out how to order/eval the numbers
by perlynewby (Scribe) on Jun 25, 2015 at 00:56 UTC | |
by roboticus (Chancellor) on Jun 25, 2015 at 02:23 UTC | |
by perlynewby (Scribe) on Jun 25, 2015 at 19:32 UTC | |
by perlynewby (Scribe) on Jun 27, 2015 at 02:22 UTC |