Perl Access Modifier

1) my:
  1. Using this you can declare any variable which is specific within the block. i.e. within the curly braces.
  2. Since the scope of local variables are limited to the block, you can use same name local variables in different blocks without any conflicts.
  3. The variable declared using my keyword, at the beginning of the programs right after pragmas would be accessible throughout the program.
  4. Lexical variables are created using 'my' keyword. They are private variables.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/usr/bin/perl
use strict;
use warnings;
my $age =29;

if (1<2){
    print "Age = $age\n";    
}

print "Age = $age\n";

2) local:
  1. Using local we can mask the same variable values to different values without actually changing the original value of the variable.
  2. suppose we have a variable $var for which the value is assigned 5, you can actually change the value of that variable by re-declaring the same variable using local keyword without altering the original value of the variable which is 5.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/usr/bin/perl

$var = 5;

{
local $var = 3;
print "local,\$var = $var \n";
}

print "global,\$var = $var \n";
Output:
local,$var = 3
global,$var = 5

3) Our:
  1. Once a variable is declared with access modifier "our" it can be used across the entire package.
  2. This variable can be accessed in any scripts which will use that package.

<-- Previous || Next -->

1 comment: