[Web4lib] global variables versus local variables

Darryl Friesen Darryl.Friesen at usask.ca
Thu May 26 12:01:16 EDT 2005


 
Sorry to jump in so late; just catching up on web4lib.

John Fitzgibbon wrote:

> However, defining a variable within a sub-routine, as in VbScript,
> means the variable is defined every time the sub-routine is run
> whereas defining it outside the sub-routine means the variable is
> defined only once. Why is it more efficient to define a variable
> within a sub-routine?

I wouldn't worry about efficiency, at least not with respect to where your
variables are declared.  You needn't worry that if your function or
subroutine is called many times, that additional memory or resources will be
wasted (unless you are talking about recursive functions). Theoretically,
local variables "disappear" as the scope changes; i.e. the memory and/or
resources they used are deallocated.

Brandon Dennis wrote:

>This is one of the reasons I never liked working with PERL
> programming, because it tends to become a mish-mash of spaghetti
> code that is very difficult to debug or change.   It may just be
> the stuff I've looked at, and I'm sure that quality Perl programmers
> can do amazing things with structure.

The first line of every Perl script I write is:

    use strict;

That'll force some better coding upon you (strict variable scoping and
declaration among other things).  If you really want clean code, change the
normal

    #!/usr/bin/perl

To

    #!/usr/bin/perl -w

Which will cause Perl to generate warnings for a number of different
situations (variable declared by never used etc etc).  None of this will
stop a programmer from writing those really cool obfuscated Perl statements
that take forever to remember what they did, but at least your variables
will be properly declared.

- Darryl

 ----------------------------------------------------------------------
  Darryl Friesen, B.Sc., Programmer/Analyst    Darryl.Friesen at usask.ca
  Education & Research Technology Services,     http://gollum.usask.ca/
  Information Technology Services Division,
  University of Saskatchewan
 ----------------------------------------------------------------------
  "Go not to the Elves for counsel, for they will say both no and yes"



More information about the Web4lib mailing list