Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Our, use vars, and magic, oh my!

by dga (Hermit)
on Aug 23, 2001 at 19:32 UTC ( [id://107366]=note: print w/replies, xml ) Need Help??


in reply to Our, use vars, and magic, oh my!

Update: can't believe I missed an important point. This is only if these are declared in a seperate block. D'oh.

my $x; if($test) { my $z; func(); } sub func { #cant see $z #can see $x since the sub is in the same scope as $x }

Mea Culpa.

1.Is there any difference between declaring variables at the beginning of scripts with my or our? Won't their scope be the same?
2.Is there a reason to use one or the other in this situation

1. The scope is the same. our variables cannot be used outside the current file (unless they are declared in the other file of course). In the file there is an important difference though. our variables can be seen in subroutines and my variables declared at the top of your script cannot be seen inside your subroutines. You must pass them in.

2. If you don't want your subs to see the variables without being passed in ( ie as global ) then you should use my.

Replies are listed 'Best First'.
Re: Re: Our, use vars, and magic, oh my!
by Hofmator (Curate) on Aug 23, 2001 at 19:47 UTC

    our variables can be seen in subroutines and my variables declared at the top of your script cannot be seen inside your subroutines.
    This is only true if you put your subroutines above the top of the script, i.e. above the my declarations.

    Some code - where $var can be accessed in the subroutine:

    use strict; my $var = 4; sub foo { $var = 'bar'; } foo; print $var;

    -- Hofmator

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-26 01:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found