Local and Global variables in perl

前端 未结 4 1356
不思量自难忘°
不思量自难忘° 2020-12-03 21:09

I am having few doubts about the local/our scope in Perl. I read a lot of documentation, but I am still in confusion is there. Following are the confusions

4条回答
  •  盖世英雄少女心
    2020-12-03 21:33

    Example 1:

    sub mess_with_foo {
          $foo=0;
     }
    
     sub myfunc {
          my $foo=20;
          mess_with_foo();
          print $foo;
     }
     myfunc();
    

    Example 2:

     sub mess_with_foo {
          $foo=0;
     }
    
     sub myfunc {
          local $foo=20;
          mess_with_foo();
          print $foo;
     }
     myfunc();
    

    Example 1 prints 20 because mess_with_foo() could not see my $foo. It could not change it. my $foo can only be seen in its scope of myfunc().

    Example 2 prints 0 because mess_with_foo() can see my $foo and change it. local $foo can be seen in its scope of myfunc() AND in the scope of any function called from within its scope of myfunc().

    That's the only difference. Neither my $foo nor local $foo will be seen outside of their scope of myfunc().

提交回复
热议问题