Anonymous Variables: If a variable is declared in anonymous mode, it treats like memory allocation. It's important first to understand how your OS and libraries handle memory and depends on 32-bit/64-bit machine.
These variables are not referred by names.
Let's look into the details how PERL handles these variables...
Scalar Variable Handling Array values...
A reference is a scalar value and can refer to any other Perl data type.
A scalar variable can be declared providing list of array values.
>my $Scal = [1, 2, 3, 4];
Here the scalar variable wont handle the list of values, it handles the address where the array is located.
Each and every variable in the list is accessed using its index.
For Example:
#Annonymous for ARRAY
my $var1 = [1,2,3];
print("Array details are ");
foreach (@{$var1})
{
print ;
}
Result:
Array details are 123
Note: @{var1} is an array, but when it is used in scalar context then it returns number of elements contained in it.
Scalar Variable Handling Hash Variables...
Storing a reference as the value of an hash element, can easily create lists and hashes within lists and hashes.
For Example:
#Annonymous for HASH
my $var1 = { aa => "Synergy", ab => "Change", ac => "Integrations" };
foreach ( keys(%$var1) ) #returns the Key values for Hash Variable
{
print "$$var1{$_} \n";
}
Result:
Change
Integrations
Synergy
Here '$_' refers to "default variable",It's used as the default argument to a number of functions in Per
For obtaining individual values we need to refer to each elementFor Example:
#Annonymous for HASH
my $var1 = { aa => "Synergy", ab => "Change", ac => "Integrations" };
print "\nFirst Value =>" ,"$var1->{'aa'}" . "\n";
Result:
First Value =>Synergy
Here it goes another interesting example...
my $var1 = { aa => { a => 'Change', b => 'Integration'} };
print "$var1->{'aa'}->{'a'}\n";
Result:
Change
This is 2 level hash of hash structure using anonymous hash references. Sounds Cool!!!
No comments:
Post a Comment