I know this has been answered already, but let me just expand a bit.
in general in perl we would work in blocks, if we can call it that. If you set
my $string = 'String';
in the beginning of the script, outside any loop, that declaration will stay the string throughout the script, unless you re-declare or re-assign it somewhere along the line.
my $string = 'string';
$string = 'Text';
That changes a bit if you work inside of a block, let's say in an if statement:
Scenario 1.
my $var = 'test';
if ($var =~ /test/) {
my $string = 'string';
}
print $string; # This will not work as $string only existed in the if block.
The following is the same scenario, but you re-declare $var
in the if block and therefore it will try and match the new variable which has no value and therefore $string
in this instance will never be set.
Scenario 2.
my $var = 'test';
if (my $var =~ /test/) {
my $string = 'string';
}
There is another one though which works differently from my
and that is our
Scenario 3.
my $var = 'test';
if ($var =~ /test/) {
our $string = 'string';
}
print $string;
The above scenario works a bit different from scenario 1. We are declaring our $string
inside of the if statement block and we can now use $string outside of that loop because our
is saying any block from here on, owns this variable.