Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: $_ scoping issues

by tilly (Archbishop)
on Jul 14, 2003 at 19:39 UTC ( #274127=note: print w/replies, xml ) Need Help??


in reply to $_ scoping issues

See $_ haters anonymou for a discussion of the scoping of $_.

If you wish to use it widely in loops, then it is up to you to either localize it before calling anything that manipulates it, or to localize it before assigning to it.

It is, of course, better to never assign to $_ without localizing it, but you can't always control other people's code. Therefore the paranoid call local on $_ early and often.

Replies are listed 'Best First'.
Re: Re: $_ scoping issues
by pemungkah (Priest) on Jul 15, 2003 at 16:18 UTC
    All very correct. To specifically state it: $_ is a global variable, and is shared between all packages.

    This means that if you use it, you should use local() to be polite to your callers, and you should be careful to insulate yourself from code that may alter it.

    This can be a difficult proposition if you didn't write the code yourself (and sometimes even if you did!). Generally, you have to look at each appllication of $_ and judge on a case-by-case basis whether someone else may be modifying it while you're using it.

    Your best protection is to get into the habit of always localizing it yourself, so as not to step on someone else's toes, and to not trust that code you call has always been so polite.

      To more precisely state it, no matter what package has been declared, $_ means $main::_.

      As an amusing side effect, the declaration our $_; will (if you are in any package other than main) cause your explicit references to $_ to not be the $_ that you expect...

      thanks guys, these are the kind of things that a former C programmer needs to learn about programming in perl =)

      these forums are terrific, I've learned a lot over the last day browsing through the nodes. What a helpful community!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://274127]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2023-02-06 10:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (33 votes). Check out past polls.

    Notices?