Why declare Perl variable with "my" at file scope? -
i'm learning perl , trying understand variable scope. understand my $name = 'bob'; declare local variable inside sub, why utilize my keyword @ global scope? habit can safely move code sub?
i see lots of illustration scripts this, , wonder why. use strict, doesn't complain when remove my. i've tried comparing behaviour , without it, , can't see difference.
here's one example this:
#!/usr/bin/perl utilize strict; utilize warnings; utilize dbi; $dbfile = "sample.db"; $dsn = "dbi:sqlite:dbname=$dbfile"; $user = ""; $password = ""; $dbh = dbi->connect($dsn, $user, $password, { printerror => 0, raiseerror => 1, autocommit => 1, fetchhashkeyname => 'name_lc', }); # ... $dbh->disconnect; update it seems unlucky when tested behaviour. here's script tested with:
use strict; $a = 5; $b = 6; sub print_stuff() { print $a, $b, "\n"; # prints 56 $a = 55; $b = 66; } print_stuff(); print $a, $b, "\n"; # prints 5566 as learned of answers here, $a , $b special variables declared, compiler doesn't complain. if alter $b $c in script, complains.
as why utilize my $foo @ global scope, seems file scope may not global scope.
it's practice. personal rule, seek maintain variables in smallest scope possible. if line of code can't see variable, can't mess in unexpected ways.
i'm surprised found script worked under use strict without my, though. that's not allowed:
$ perl -e 'use strict; $db = "foo"; $db' global symbol "$db" requires explicit bundle name @ -e line 1. global symbol "$db" requires explicit bundle name @ -e line 1. execution of -e aborted due compilation errors. $ perl -e 'use strict; $db = "foo"; $db' foo variables $a , $b exempt:
$ perl -e 'use strict; $b = "foo"; $b' foo but don't know how create code posted work strict , missing my.
perl scope
No comments:
Post a Comment