PERL Referencing and Dereferencing
Intro
PERL - Practical Extraction and Report Language.
Referencing a variable means creating a pointer to the variable.
Referencing in C is done by the & operator, but in PERL referencing is done by the \(backslash) operator.
Check out the following examples to understand better:
my $scalar = "http://digitalpbk.blogspot.com";
my $scalar_ptr = \$scalar; //Scalar reference
my $array= (1,2,4,3,5);
my $array_ptr = \@array; //Array reference
//or
my $array_ptr = [1,2,3,4,5];//Array reference
//Note the [Square brackets]
my %hash = ("one",1,"two",2);
my $hash_ptr = \%hash; //Hash reference
//or
my $hash_ptr = {"one" => 1,"two"=>2};//Hash reference
//Note the {Curly brackets}
my $sub_ref = \&a_subroutine;//Subroutine reference
//or
my $sub_ref = sub { print "somethings"; };//Sub reference
Dereferencing is the opposite of referencing i.e, to get the value pointed by the referencing/pointing variable. Dereferencing in C is done by the * operator, whereas in PERL it is done by prepending, adding an appropriate @,$ or % to the reference variable.
my $scalar_ptr = \$scalar; //Scalar reference
my $scalar = $$scalar_ptr; //Scalar Var
my $array_ptr = \@array; //Array reference
//or
my $array_ptr = [1,2,3,4,5];//Array reference
my $array = @$array; // Array Var
my $hash_ptr = \%hash; //Hash reference
my %hash = %$hash //Hash Var
my $sub_ref = \&a_subroutine;//Subroutine reference
my $sub_ref = sub { print "somethings"; };//Sub reference
&$sub_ref //Call Subroutine
Thats all about referencing and dereferencing...
2 comments:
in the derefrencing section, shouldn't the line:
my $array = @$array; // Array Var
be instead:
my $array = @$array_ptr; // Array Var
?
Yes, I thought it, too. The same on this line:
my %hash = %$hash //Hash Var
right:
my %hash = %$hash_ptr //Hash Var
Post a Comment