in reply to map and grep syntax question

ouch. if you'd used warnings you'd get a warning about the "if" statement. The problem is that your comma at the end of the if() statement tries to combine $_ in the same statement. It doesn't really make much sense, and I'm not sure what the perl interpreter makes of it either. Anyway, you want a semicolon there:
#!/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' } ];
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.

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
    thanks for update2. it's what i needed, and i hadn't even thought of doing the check in the list construction using map
Re^2: map and grep syntax question
by Jenda (Abbot) on Dec 11, 2004 at 22:27 UTC

    I think it would be a bit more readable like this:

    my $newLoop = [ map {$_ eq $row->{title} ? {'PARTNAME' => $_, 'SELECTED' => 1} : { +'PARTNAME' => $_} } @$parts ] ; #or even my $newLoop = [ map { if($_ eq $row->{title}) { {'PARTNAME' => $_, 'SELECTED' => 1} } else { {'PARTNAME' => $_} } } @$parts ] ;

    Jenda
    We'd like to help you learn to help yourself
    Look around you, all you see are sympathetic eyes
    Stroll around the grounds until you feel at home
       -- P. Simon in Mrs. Robinson