bipinbalan has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I given the two scripts below. the two scripts will give the same output. But in the first one, I used pass by reference and the second, I used "local".
#### Script 1 : #####

#!/usr/bin/perl -w use strict; &foo1; sub foo1 { my $first=1; &foo2(\$first); print "$first\n"; } sub foo2 { my $second=shift; print "$$second\n"; $$second++; }

#### Script 2 : #####

#!/usr/bin/perl -w use strict; use warnings; &foo1; sub foo1 { local $b=1; &foo2; print "$b\n"; } sub foo2 { print "$b\n"; $b++; }

My doubt is that which program is more efficient ? Whether we can use "local" instead of "pass by reference" ?


Hoping for the reply.

  Bipin Balan

Replies are listed 'Best First'.
Re: using local and pass by reference method
by ysth (Canon) on Feb 11, 2008 at 11:33 UTC
    Don't worry about it? I strongly doubt you'll see any difference. local() is probably more bug-prone, so of the two, I would pass by reference.

    By the way, to call a subroutine with no parameters, you usually want to provide empty parentheses: &foo1();. &subname with no parenthesis is a special form of subroutine call that you will rarely need to use, and that may bite you when used inadvertently.

Re: using local and pass by reference method
by hipowls (Curate) on Feb 11, 2008 at 10:56 UTC

    Efficient for what? Speed or maintainability? Assigning a reference is pretty low cost and lexical variables are slightly more efficient. It's probably much of a muchness either way but you should benchmark if you need to know.

    use Benchmark; cmpthese ( -1, { local => sub { ... }, value => sub { ... }, );

    Personally I'd use lexical variables and if copying was expensive or I wanted to modify the arguments use $_[0] etc or Data::Alias if I refer to an argument more than once or need to document it's purpose. For example

    use Data::Alias; sub sample { alias $html = $_[0]; ... }

Re: using local and pass by reference method
by stiller (Friar) on Feb 11, 2008 at 12:02 UTC
    It might be that using local is more effective than passing by reference (but I'm almost certain it isn't, but you could benchmark that), but that use of local is evil.

    Seeing local is a flag, it says something about what you are doing, and that something is not supposed to be effective, but conseptually rather to temporarily alter a global/wider scope resource, with a promise to restore it when you go out of scope and without affecting others using it elsewhere.

    hth

Re: using local and pass by reference method
by Narveson (Chaplain) on Feb 11, 2008 at 14:55 UTC