Wednesday, July 21, 2010

Reference to arrays

Aim: Accessing elements from reference to array. Define an array, put reference to that and access elements from that reference,

@arr = qw(apple orange banana);

##reference to this array is ==> ref_to_arr scalar

$ref_to_arr = \@arr; ### \ indicates address of @arr
(OR)
$ref_to_arr{name} =\@arr; ### includes accessing elements of referenced array

####Accessing elements (foreach)###########

foreach $ele (@$ref_to_arr) {
print " Array elements: $ele \n";
}

foreach $ele (@{ $ref_to_arr{name} }) {
print " Array elements: $ele \n";
}

####Accessing elements (for)###########

for ($i=0; $i <= $#$ref_to_arr; $i++) {
print "Array element: $ref_to_arr->[$i] \n";
}


for($i=0; $i <= $#{ $ref_to_arr{name} }; $i++) {
print "Array element: $ref_to_arr{name}{$i} \n";
}

No comments:

Post a Comment