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

OK, I'm playing with WWW::Mechanize at the moment and it's thrown up what is for me an interesting question, and a good chance to learn about references

TO quote WWW::Mechanize one of the pieces of information that can be retrieved is a reference to an array containing an array reference for every <A> and <FRAME> tag and that for each <A> tag, element[0] contains the text of the href and element[1] contains the text enclosed by the <A> tag

Through reading some of the tutorials and various chunks of perl books, I've come up with the following code which will let me view all of (say) the element[0]'s:

foreach (@{$w->{links}}) { print $$_[0]."\n"; }

Now what I'd really like is to generate an array containing all of the element[0]'s which I can obviously do using the above loop and pushing onto an array - but is there some easy way through referencing that would let me do it without the loop?

Replies are listed 'Best First'.
Re: References and arrays
by zigdon (Deacon) on Oct 08, 2002 at 17:57 UTC

    Untested, but this seems like a classic case for map:

    @text = map {$_->[0]} @{$w->{links}};

    See map

    -- Dan

      You know what - I wish I could vote for this reply twice. For some reason, I think it might finally be the example that's let me get my head around map

      Thanks again

      Thanks for that - seems to do the trick

Re: References and arrays
by sauoq (Abbot) on Oct 08, 2002 at 18:02 UTC
    is there some easy way through referencing that would let me do it without the loop?

    No, because the elements you want live in different arrays. It doesn't matter that the arrays they live in are all referenced by elements of yet another array. You still have to iterate over them.

    Something like the following would probably be better than a for loop where you push each element on to an array though.

    @links = map { $$_[0] } @{$w->{links}}
    -sauoq
    "My two cents aren't worth a dime.";