Re: OO Perl, iterators



Anno Siegel wrote:

> Gregory Toomey <nobody@xxxxxxxxxxx> wrote in comp.lang.perl.misc:
>> I'm a bit confused about the Perl OO syntax. From my reading "foreach"
>> acts as an iterator.
>
> It is a loop construct. An iterator is something that produces
> values to iterate over, like <> or "each" in Perl.
>
>> Any somebody tell me in the standard example below:
>
> For all of these, do
>
> my @answers = $query->answer;
>
>
>> - how to count the total number of $query->answer
>
> my $total = @answers;
>
>> - how to access the i'th answer; $query->answer[$i] does not work
>
> my $i_th = @answers[ $i];
>
>> - how to access a random answer
>
> my $rand_ans = @answers[ rand @answers];
>
>> thanks
>> gtoomey
>> --
>> use Net::DNS;
>> my $res = Net::DNS::Resolver->new;
>> my $query = $res->query("example.com", "NS");
>>
>> if ($query) {
>> foreach $rr (grep { $_->type eq 'NS' } $query->answer) {
> ^^^
> You're not running under strict! You've been around long enough to
> know better.
>
>> print $rr->nsdname, "\n";
>> }
>> }
>
> Anno

That code was from the NET::DNS module.

I think I found the answer to my original question.
The syntax $query->answer[$i] is wrong; ($query->answer)[$i] works even
though it looks strange.

gtoomey
.



Relevant Pages

  • Re: while each hash, why not array
    ... :> Anno Siegel wrote on MMMDCCV September ... :> have slots to keep the state of the iterator. ... :> them to arrays means adding an extra integer to all AVs. ... I wonder how Perl 6 will behave in that respect. ...
    (comp.lang.perl.misc)
  • Re: while each hash, why not array
    ... > Anno Siegel wrote on MMMDCCV September ... > them to arrays means adding an extra integer to all AVs. ... Having the iterator incorporated in the hash itself isn't ideal -- it's ...
    (comp.lang.perl.misc)