linux poison RSS
linux poison Email

Perl Script: Creating pointers (References) to variable, Array and Hash

A reference is a scalar value that points to a memory location that holds some type of data. Everything in your Perl program is stored inside your computer's memory. Therefore, all of your variables, array, hash and functions are located at some memory location. References are used to hold the memory addresses.

Below is simple Perl script which demonstrate the usage of reference ...

Source: cat pointer.pl
#!/usr/bin/perl

# Creating pointer to a variable.
$var = 10;
$pointer = \$var;
print "Pointer address is: $pointer \n";
print "value store at $pointer is $$pointer \n";

print "--------------------------------\n";

# Creating pointer to an array.
@array = ("1", "2", "3", "4");
$array_pointer = \@array;
print "Address of the array in the memory: $array_pointer \n";

$len = scalar(@$array_pointer);
print "Length of the array: $len \n";

for ($i=0; $i<$len; $i++) {
  print "$$array_pointer[$i] \n";
}
print "--------------------------------\n";

# Creating pointer to a hash
%hash = (
  "01", "A",
  "02", "B",
  "03", "C"
);

$hash_pointer = \%hash;
print "Address of the hash in the memory: $hash_pointer \n";

foreach $key (sort keys(%$hash_pointer)) {
  print "$$hash_pointer{$key} \n"
}

Output: perl pointer.pl
Pointer address is: SCALAR(0xd4d2a8)
value store at  SCALAR(0xd4d2a8)  is 10
--------------------------------
Address of the array in the memory: ARRAY(0xd59d88)
Length of the array: 4
1
2
3
4
--------------------------------
Address of the hash in the memory: HASH(0xd5a088)
A
B
C




0 comments:

Post a Comment

Related Posts with Thumbnails