I am learning Perl and trying to understand the scope of a variable. I understand that it my $name = 'Bob';will declare a local variable inside sub, but why are you using the keyword myin the global scope? This is just a good habit, so can you safely move the code to sub?
I see many examples of scripts that do this, and I wonder why. Even when use stricthe does not complain when I delete my. I tried to compare the behavior with him and without him, and I see no difference.
Here is one example that does this:
use strict;
use warnings;
use DBI;
my $dbfile = "sample.db";
my $dsn = "dbi:SQLite:dbname=$dbfile";
my $user = "";
my $password = "";
my $dbh = DBI->connect($dsn, $user, $password, {
PrintError => 0,
RaiseError => 1,
AutoCommit => 1,
FetchHashKeyName => 'NAME_lc',
});
$dbh->disconnect;
Update
It seems I was unlucky when I tested this behavior. Here's the script I tested:
use strict;
my $a = 5;
$b = 6;
sub print_stuff() {
print $a, $b, "\n";
$a = 55;
$b = 66;
}
print_stuff();
print $a, $b, "\n";
, $a $b , , . $b $c script, .
my $foo , , .