Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Global variable vs passing variable from sub to sub

by gmpassos (Priest)
on Sep 14, 2004 at 05:24 UTC ( #390746=note: print w/ replies, xml ) Need Help??


in reply to Global variable vs passing variable from sub to sub

Humm, don't forget that Perl uses a special variable @_ for the arguments. What you can't forget is that this array @_ is global, but it's elements will change for each call. So, the performance of @_ will be similar to a global variable, but will work as a stack, so, will work for multiple calls of the same sub and recursivelly.

This code will show that:

sub test1 { ++$_[0] ; print "T1 [@_]\n" ; test2($_[0]) ; } sub test2 { ++$_[0] ; print "T2 [@_]\n" ; test3($_[0]) ; } sub test3 { ++$_[0] ; print "T3 [@_]\n" ; print "end\n" ; } my $n = 10 ; test1($n) ; print "N: $n\n" ;
output:
T1 [11] T2 [12] T3 [13] end N: 13
And forget the use of a global variable for any type of code and start learning OO. Take a look at perlobj, perltoot, perlboot and perltooc.

For Object Orientation (OO) I use Class::HPLOO.

Graciliano M. P.
"Creativity is the expression of the liberty".


Comment on Re: Global variable vs passing variable from sub to sub
Select or Download Code
Re^2: Global variable vs passing variable from sub to sub
by kiat (Vicar) on Sep 14, 2004 at 07:11 UTC
    Thanks for your input, gmpassos!

    I would love to switch to the OO mode some day. I've read quite a bit on it and have even got some OO code to work (got some help from castaway). Still, I'm not quite ready yet. Maybe it's just that I think better in terms of procedures (verbs rather than nouns).

    I suppose if I were to write a specific standalone module that serves a single purpose, I might be able to think the OO way much better.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (16)
As of 2015-07-06 13:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (74 votes), past polls