daniel85 has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
I have encountered a quite crazy issue with Perl. Please look at the following example:
{ package FooObj; sub new { bless { _count => 1, _data => 0 }, $_[0] } sub add_data { my $self = shift; my $data = shift if (@_); print "\nCalled: data value is " . ($data || "NONE") . "\n"; if (defined $data) { die "\nError: data does not look like num +ber\n\n" if ($data !~ /^\d+$/); } if ($self->{_count}) { $data = 5 if (!defined $data); $self->{_data} += $data; $self->{_count}--; return($self->{_data}); } } } my $bar = FooObj->new; while(my $val = $bar->add_data()) { # do something here }
In the above example, the method add_data() should be called twice. Both times, the method is called with no argument, therefore the private variable $data should be undefined. Later on, inside the method, if $data was not defined, it gets assigned a value of 5.
Here comes the weird part. If you run the above code, it outputs:
Called: data value is NONE
Called: data value is 5
It looks like, the second time add_data() gets called, $data did not go out of scope and its previous value is still there.
However, if I replace the line my $data = shift if (@_); with my $data = shift;, I get the expected output:
Called: data value is NONE
Called: data value is NONE
Can someone please explain me what is going on? Is this a Perl bug or am I missing something??
Thanks!!!
Cheers,
Daniel
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Private variable in class method does not go out of scope ( 'my $x if...' / updated)
by LanX (Saint) on Jul 08, 2024 at 10:34 UTC | |
|
Re: Private variable in class method does not go out of scope
by Happy-the-monk (Canon) on Jul 08, 2024 at 10:36 UTC | |
by daniel85 (Novice) on Jul 08, 2024 at 10:54 UTC | |
|
Re: Private variable in class method does not go out of scope
by Anonymous Monk on Jul 09, 2024 at 11:53 UTC |