Scope of variables in a function

Gareth Kirwan gbjk at
Sat Jun 1 18:05:15 BST 2013

On 13-06-01 05:43 PM, Andrew Beverley wrote:
> Could somebody explain why the following code prints "barbar" rather
> than "bar" please? I am trying to understand why the $result variable in
> the search function retains its value the second time the function is
> called.
> ...
> sub search($)
> { ...
>    my $result = "FOO" if $in =~ /foo/;
Because your my statement is conditional. You dangled an if.
It's never run, but warnings aren't triggered because of the my 
statement's existence (which seems fair, really).
So $result is never initialized, and retails last assigned value.



More information about the mailing list