Scope of variables in a function

Andrew Beverley andy at
Sat Jun 1 17:43:40 BST 2013

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 mailing list