How should I use the “my” keyword in Perl?

后端 未结 3 1597
温柔的废话
温柔的废话 2020-11-29 00:38

I keep seeing the \"my\" keyword in front of variable names in example Perl scripts online but I have no idea what it means. I tried reading the manual pages and other site

3条回答
  •  不知归路
    2020-11-29 01:17

    Quick summary: my creates a new variable, local temporarily amends the value of a variable

    In the example below, $::a refers to $a in the 'global' namespace.

    $a = 3.14159;
    {
      my $a = 3;
      print "In block, \$a = $a\n";
      print "In block, \$::a = $::a\n";
    }
    print "Outside block, \$a = $a\n";
    print "Outside block, \$::a = $::a\n";
    
    # This outputs
    In block, $a = 3
    In block, $::a = 3.14159
    Outside block, $a = 3.14159
    Outside block, $::a = 3.14159
    

    ie, local temporarily changes the value of the variable, but only within the scope it exists in.

    Source: http://www.perlmonks.org/?node_id=94007

    Update

    About difference between our and my please see

    • What is the difference between my and our in Perl?

    (Thanks to ThisSuitIsBlackNot).

提交回复
热议问题