Professional Documents
Culture Documents
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40); // - can be used instead
of
The values can be extracted/ sliced from the hash table using Arrays
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
@array = @data{-JohnPaul, -Lisa};
print "Array : @array\n";
Result: Array : 45 30
You can get the size - that is, the number of elements from a hash by using the scalar context on
either keys or values. Simply saying first you have to get an array of either the keys or values and
then you can get the size of array as follows
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size:
is $size\n";
Adding a new key/value pair can be done with one line of code using simple assignment
operator. But to remove an element from the hash you need to use delete function as shown
below in the example
#!/usr/bin/perl
%data
@keys
$size
print
= ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
= keys %data;
= @keys;
"1 - Hash size: is $size\n";
6. What is a subroutine?
A subroutine is like a function called upon to execute a task.
subroutine is a reusable piece of code.
15. There are three loop control keywords: next, last, and redo.
The next keyword skips the remainder of the code block, forcing the loop to proceed to the next
value in the loop.
The last keyword ends the loop entirely, skipping the remaining statements in the code block, as
well as dropping out of the loop.
The redo keyword reexecutes the code block without reevaluating the conditional statement for
the loop.
my %seen = ();
my @r = ();
foreach my $a (@_) {
unless ($seen{$a}) {
push @r, $a;
$seen{$a} = 1;
}
}
return @r;
}
or
my %unique = ();
foreach my $item (@array)
{
$unique{$item} ++;
}
my @myuniquearray = keys %unique;
print "@myuniquearray";