Re: OO Perl, iterators
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxxx (Anno Siegel)
- Date: 31 Oct 2005 11:48:25 GMT
Gregory Toomey <nobody@xxxxxxxxxxx> wrote in comp.lang.perl.misc:
> 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.
So? You are responsible for the code you post, even if you take it from
somewhere else.
> 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.
It's a normal list slice, nothing strange about it. However, it
will calculate the entire list of answers each time you want to
extract a single element. Caching the list, as in my code above,
avoids that.
Anno
--
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
.
- References:
- OO Perl, iterators
- From: Gregory Toomey
- Re: OO Perl, iterators
- From: Anno Siegel
- Re: OO Perl, iterators
- From: Gregory Toomey
- OO Perl, iterators
- Prev by Date: Re: OO Perl, iterators
- Next by Date: Re: OO Perl, iterators
- Previous by thread: Re: OO Perl, iterators
- Next by thread: Re: OO Perl, iterators
- Index(es):
Relevant Pages
|