Using Reference (Part 10)-- Perl Study Notes
Create explicit reference
$sv="hello";
@av=qw(1 2 hello);
%hv=qw(k1 v1 k2 v2);
$rs=\$sv; #create $sv reference named $rs;
$ra=\@av; #create $av reference named $ra;
$rh=\$hv; #create $hv reference named $rh;
$ra->[0]; #return first value of the array;
$rh->{"k1"}; #return value of k1 of the hash;
$ra->[0,1,2]; # same as $ra->[2];
Create anonymous reference
$rs=\"hello world"; # create an scalar referecne named $rs;
$ra=[1,2,"hello"]; # create an array reference named $ra;
$rh={"k1","v1","k2","v2"}; # create an hash reference named $rh;
Dereferencing
must use @$sa,%$sh,$$ss to dereferce the array, hash and scalar variable
Querying a Reference
$a=10;
$ra=\$a;
ref($a); return false since $a is a scalar not a referecne
ref($ra); return SCALAR scine $ra is a scalar reference
Symbolic Reference
$x=10;
$var="x";
$$var=30; # $var will be replaced by x. $$var=30 will look as $x=30
$var="x";
@$var=(1,2,3); # sets @x to (1,2,3)
It is important to note that symbolic references work only for global variables
Subroutine References
References to Named Subroutines
sub great{
print "hello world\n";
}
$rs=\&grett; # create a reference to subroutine great
$rs=\&greet(); # this does not create a reference to subroute great but a reference to the return value
References to Anonymous Subroutines
$rs=sub{
print "hello \n";
}
Dereferencing subroutine References
&$rs(10,20); # call the subroutine indirectly
$rs->(10,20); #same as above
Symbolic Reference
sub foo { print "foo called\n"}
$rs="foo";
&$rs(); # call foo subroutine and print "foo called"
No comments:
Post a Comment