Scope of variables in a function
hakim.cassimally at gmail.com
Sat Jun 1 18:03:33 BST 2013
I believe your problem is:
my $x = 'FOO' if $condition;
This only declares the new variable if $condition, so it ends up having
surprising, static-like behaviour, which you probably shouldn't rely on.
$result = 'FOO' if ...
gives your expected result.
On 1 June 2013 17:43, Andrew Beverley <andy at andybev.com> 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
> Up until now I had thought that variables in a function defined with
> "my" would be empty each time the function was called, so this has
> caught me out.
> The code is just proof of concept: I realise that it could be written
> more efficiently!
> sub search($)
> my $in = shift;
> my $result = "FOO" if $in =~ /foo/;
> $result = $1 if ($in =~ /^(bar)/);
> return $result;
> print search("bar");
> print search("none");
More information about the london.pm