Why declare a Perl variable with "my" in the file area?

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:

#!/usr/bin/perl
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"; # prints 56
    $a = 55;
    $b = 66;
}

print_stuff();
print $a, $b, "\n"; # prints 5566

, $a $b , , . $b $c script, .

my $foo , , .

+4
4

. , . , .

, , script use strict my. :

$ perl -E 'use strict; $db = "foo"; say $db'
Global symbol "$db" requires explicit package name at -e line 1.
Global symbol "$db" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.
$ perl -E 'use strict; my $db = "foo"; say $db'
foo

$a $b :

$ perl -E 'use strict; $b = "foo"; say $b'
foo

, , , my.

+2

my , - Perl, , , - .

, $variable. .

$variable = 5;

# intervening assignments and calculations...

if ( $varable + 20 > 25 ) # don't use magic numbers in real code
{
    # do one thing
}
else
{
    # do something else
}

, use strict; , my? # do one thing . , .

+3

A sub / {}, . , , my "" , "" . Private Variables via my() perlodoc perlsub .

, SO, :

perlmonks node - Scope Perl: - : -)

, YAPC:: NA 2012 - () - , perl perl .

, my Perl, Javascript var - , Perl perl, , , .

ps: Javascript "" , my sub.

+1

:

  • strict , my ( state) - our use vars () .

  • . , .

  • ( .)

  • , . "" "" , , , . .

  • . my , .

    {   my $visible_in_this_scope_only;
        ...
        sub bananas {
            ...
            my $bananas = $visible_in_this_scope_only + 3;
            ...
        }
    } # End $visible_in_this_scope_only
    

( : . , ( ), , , "".

+1

Source: https://habr.com/ru/post/1545418/


All Articles