knewter has asked for the wisdom of the Perl Monks concerning the following question:

I'm going through the excellent O'Reilly's Spidering Hacks and I can't quite grasp what's going on in this line:

my @urls = map { $_->[0] } @links;

Any help? @links is (surprise) an array of links...

Replies are listed 'Best First'.
Re: map confusion
by dragonchild (Archbishop) on Jan 19, 2005 at 19:39 UTC
    map executes the command in {} on each of the elements in the the array and creates an array with the return values.

    So, if @links is an array of arrays, then @urls will be an array of the first elements in each of the sub-arrays in @links.

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

Re: map confusion
by mpeters (Chaplain) on Jan 19, 2005 at 19:40 UTC
    It's basically the equivalent of this
    my @urls; foreach (@links) { push(@urls, $_->[0]); }
    This means that since @links is an array of arrays, it will on ly use the first value in each of those arrays to place in @urls
Re: map confusion
by holli (Abbot) on Jan 19, 2005 at 19:43 UTC
    say @links looks like this:
    @links = ( [1,2,3], [4,5,6], [7,8,9] );
    and you apply
    my @urls = map { $_->[0] } @links;
    @urls will end up as
    @urls = (1,4,7);

    basically the code will produce a list that consists of the first elements of the anonymous arrays in @links.
    see perlref

    holli, regexed monk
Re: map confusion
by ccn (Vicar) on Jan 19, 2005 at 19:42 UTC

    @links is AoA, (Array of Arrays) you can see it with:

    use Data::Dumper; print Dumper(\@links);
    map{$_->[0]} returns a list which consist of first elements of each inner array
Re: map confusion
by gopalr (Priest) on Jan 20, 2005 at 05:01 UTC
    Pls. refere for more info. about map