subroutine local variable with initialization

M

Mark

Suppose I have a program with the entry point at the top and
subroutines following the exit point. I want to have a subroutine
local variable, $count in my example, that is initialized to a
starting value.

This works, but seems overly cumbersome to me. Is there a better way?

use strict;
use warnings;

# entry point
doit();
doit();
exit; # exit point before subroutine definition

{
my $count;

BEGIN {
$count = 1;
}

sub doit {
print "count=$count\n";
$count++;
}
}

__END__

Output:
count=1
count=2
 
U

Uri Guttman

M> doit();
M> exit; # exit point before subroutine definition

M> {
M> my $count;

M> BEGIN {
M> $count = 1;
M> }

M> sub doit {
M> print "count=$count\n";
M> $count++;
M> }
M> }

put the sub and count together into the begin block:

BEGIN {

my $count = 1 ;

sub doit {
print "count=$count\n";
$count++;
}
}

or use closures (plenty about that on the net so google for it)

uri
 
J

Joost Diepenmaat

Mark said:
Suppose I have a program with the entry point at the top and
subroutines following the exit point. I want to have a subroutine
local variable, $count in my example, that is initialized to a
starting value.

This works, but seems overly cumbersome to me. Is there a better way?

Some different solutions:

* put your $count variable and initialization at the top.

* put the whole $count and subroutine construct in a module and use() it
(this is probably what I would prefer to do)

* get perl 5.10 and use state() variables

* use the my $var if 0 trick - not recommended, probably.
 
U

Uri Guttman

JD> Some different solutions:

JD> * use the my $var if 0 trick - not recommended, probably.

given yours and my suggestions, let's never mention the if 0 hack again!
it may even break in future perls as it is not needed with state vars.

uri
 
B

Brian McCauley

BEGIN {

    my $count = 1 ;

    sub doit {
        print "count=$count\n";
        $count++;
    }

}

I would argue that an INIT block would be more idiomatically correct
rather than a BEGIN one.

But it does not really make any difference.
 
I

Ilya Zakharevich

[A complimentary Cc of this posting was NOT [per weedlist] sent to
Brian McCauley
I would argue that an INIT block would be more idiomatically correct
rather than a BEGIN one.
But it does not really make any difference.

.... Well, if you forget that the version with BEGIN works, and the
version with INIT works only in some situations, then yes...

Hope this helps,
Ilya
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,045
Messages
2,570,389
Members
47,052
Latest member
ketan

Latest Threads

Top