in reply to map and grep syntax question
update: Actually, your use of grep() is not at all idiomatic: you should probably not modify $_ in the grep block at all: it would be cleaner to use map() instead and return a modified copy.#!/usr/local/bin/perl -w use strict; use Data::Dumper; my $row = { title => 'Part1' }; my $parts = [ 'Part1', 'Part2','Part3' ]; my $newLoop = [ grep { $_->{SELECTED}++ if $_->{PARTNAME} eq $row->{title}; $_ } map +{ 'PARTNAME' => $_ }, @$parts ] ; warn Dumper($newLoop); __END__ $VAR1 = [ { 'SELECTED' => 1, 'PARTNAME' => 'Part1' }, { 'PARTNAME' => 'Part2' }, { 'PARTNAME' => 'Part3' } ];
update2: demonstration:
#!/usr/local/bin/perl -w use strict; use Data::Dumper; my $row = { title => 'Part1' }; my $parts = [ 'Part1', 'Part2','Part3' ]; my $newLoop = [ map +{ 'PARTNAME' => $_, $row->{title} eq $_ ? ('SELECTED' => 1) : (), }, @$parts ] ; warn Dumper($newLoop);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: map and grep syntax question
by geektron (Curate) on Dec 10, 2004 at 22:47 UTC | |
|
Re^2: map and grep syntax question
by Jenda (Abbot) on Dec 11, 2004 at 22:27 UTC |