in reply to modify list through grep

#!/usr/bin/perl # Yo, I'll tell you what I want, what I really really want, # So tell me what you want, what you really really want, # I'll tell you what I want, what I really really want, # So tell me what you want, what you really really want, # I wanna, I wanna, I wanna, I wanna, # I wanna really really really wanna zigazig ha. @l = ( "a", "b", "c" ); *m = &{sub {\@_}} (grep /a/, @l); $m[0] = "z"; print "@l\n";

Replies are listed 'Best First'.
Re^2: modify list through grep
by jdporter (Paladin) on Nov 26, 2006 at 16:30 UTC

    I was excited by your answer at first because I thought it was that trick I saw for making aliases, and which I can never remember. ;-)

    But then I realized that you're using a glob, which means you could simply write

    @l = ( "a", "b", "c" ); *m = \@l; $m[0] = "z"; print "@l\n";
    We're building the house of the future together.

      Yes, you're right. My reply was a bit tongue-in-cheek - the OP asked why his grep aliasing example "didn't work" and I resolved to beat it into submission ;)

      There's a slight difference though. *m = \@l; aliases the entire array object. The sub {\@_} trick creates a new array object containing scalar elements which are aliased to memberes in @l matching /a/ (in OP's example it contains only one element aliased to the first element in @l - "a").

        thanks, this would be a solution for me, unfortunately the code with sub still gives "a b c "
        Extended version of the code I'm trying to get to work
        foreach $p ( @patterns ) { if ( ??? grep /$p/, @values ) { modify the matching list value; } else { push @values, "strings $pattern"; } }
        For the modification part I can use grep again and modify the value through $_, but then I call expensive grep twice. If I could save a reference (alias?) into @values in the if condition statement I can have a lighter code.