Friday, August 7, 2009

Array and Hash

my @aray = ( 12, 13, 87, 238, 28, 761);
my $last_index = $#array; # it will be wrong if typed like #$aray, because it will comment out $array.
my $length = @array; # it's similar to typecasting, In this way we treating an array like a scalar

print "last index = ",$last_index,"\n"; #prints: 5
print "length of array = $length\n"; #prints: 6
print "second lat element of array = $array[-2] \n"; # prints: 28
print "fifth element = $array[4] \n"; #prints: 28

Hashes:
my %ageof = {
ram => 23,
shyam => 25,
rita => 30,
sita => 16,
};
my %fav_color = {
ram => "blue",
shyam => "white",
rita => "orange",
sita => "red",
};

"=>" is called as fat comma, it behaves same as normal comma(only it's bigger so easy to see), and it automatically quotes values to it's left, but values on right need to be quoted.

Hash Lookup:

print $ageof{shyam}; # prints 25
print $fav_color{rita}; # prints: orange

Adding Hah Pairs:

$ageof{mohan} = 47; # now mohan is added into hash %ageof;

Hash Size:

my $num_of_pairs = keys(%ageof);

Hashes don't Interpolate in quotes.

Arrays and Hashes shouldn't be passed to subroutines directly because it leads them to lost their identity, So they should be passed as reference.

if( greater_length( @array1, @array2 ) ) {
# .........
}
sub greater_length {
my ( @array1, @array2 ) = @_;
# @array1 now has "all" of the elements and @array2 is "empty"
return @array1 > @array2; # Always true!
}

# by using reference above problem can be solved

if( greater_length( \@array1, \@array2 ) ) {
# ........
}
sub greater_length {
my ( $array1, $array2 ) = @_;
my @array1 = @$array1;
my @array2 = @$array2;
return @array1 > @array2;
}

No comments:

Post a Comment