Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Spot the bug

by tlm (Prior)
on Dec 21, 2005 at 00:59 UTC ( #518216=perlmeditation: print w/replies, xml ) Need Help??

I know variants of the following bug have been discussed in the Monastery recently, but I didn't find this particular one. My apologies in advance if I missed it.

Spot the bug:

sub foo { my $hashref = shift; while ( my ( $key, $value ) = each %$hashref ) { return if sometest( $key ); frobnicate( $key, $value ); } }

BTW, there's nothing arcane about this bug. It's vanilla Perl, but it's easy to miss.

Update: The original title of this thread ("Buglet") was confusing, so, by popular demand, I changed it. I hope the new title is an improvement.

the lowliest monk

Replies are listed 'Best First'.
Re: Spot the bug
by merlyn (Sage) on Dec 21, 2005 at 01:54 UTC

      By "bug", I presume you mean "bug in your code". The "exiting from the middle of an each-loop" has been discussed here before, and the behavior of Perl is as documented.

      Sorry I gave the impression (probably through my choice of title) that I thought this was a bug in Perl. I did mean a bug in the snippet I presented. Perl's behavior is, as you say, amply documented.

      the lowliest monk

      And for small hashes, that is fine. It's less so for a general purpose function in a module - it might get passed in a large hash, possibly even one that's tied to storage on disk.
      Perl --((8:>*

        The problem is people have a bad habit of forgetting to reset the iterator, and heaven help you if the general routine calls back out to uncontrolled code from inside the loop. Can you say "infinite loop"? :-)


        Well, I'd argue that any program for which the difference between a keys-based walk and an each-based walk is significant shouldn't be using hashes that large, not with the arrival of things like DBD::SQLite or other cheap databases.

        Yes, it mattered when Perl was running on 10Mhz 1Megabyte machines, and databases were tough, so a DBM hash was a cool thing. Those are long gone. {grin}

        -- Randal L. Schwartz, Perl hacker
        Be sure to read my standard disclaimer if this is a reply.

Re: Spot the bug
by ysth (Canon) on Dec 21, 2005 at 19:16 UTC

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://518216]
Approved by ww
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2021-09-18 04:53 GMT
Find Nodes?
    Voting Booth?

    No recent polls found