Friday, January 18, 2013

How could you add or remove elements in a Hash in Perl?

%FM = ( 'Radio City' => 91.1,
              'Big FM' => 92.7,
              'Red FM' => 93.5,
              'Radio One' => 94.3,
              'Radio Mirchi' => 98.3,
              'Fever' => 104.0,
              'Oye FM' => 104.8,
              'FM Rainbow' => 107.1,
              'FM Gold' => 100.7);

# Add one more element to the hash
$FM{'FM Berhampur'} = 100.6;

# Remove one element from the hash
delete ( $FM{'FM Gold'} );

foreach ( keys %FM )
{
    print "$_ => $FM{$_}\n";
}

How could you find out size of a Hash in Perl?

%FM = ( 'Radio City' => 91.1,
              'Big FM' => 92.7,
              'Red FM' => 93.5,
              'Radio One' => 94.3,
              'Radio Mirchi' => 98.3,
              'Fever' => 104.0,
              'Oye FM' => 104.8,
              'FM Rainbow' => 107.1,
              'FM Gold' => 100.7);

print "size of Hash: ",scalar keys %FM,"\n";
# or
print "size of Hash:  " . keys ( %FM ) . ".\n";

How could you check the existance of a key in a Hash in Perl?

%FM = ( 'Radio City' => 91.1,
              'Big FM' => 92.7,
              'Red FM' => 93.5,
              'Radio One' => 94.3,
              'Radio Mirchi' => 98.3,
              'Fever' => 104.0,
              'Oye FM' => 104.8,
              'FM Rainbow' => 107.1,
              'FM Gold' => 100.7);

if (exists ( $FM { "Fever" } ) )
{
    print "Frequency of FM Fever is $FM{Fever}MHz.\n";
}

Thursday, January 10, 2013

What does bless() do?

The process of turning a reference into an object is called 'blessing' and the bless() function
just turns the reference into an object of the required class.

Thursday, January 3, 2013

What is the difference between pipe and xargs?

xargs converts the input into command line arguments and is useful when the parameter list is too long for the shell. It splits the parameter list and iterates over the smaller list.

The pipe takes the standard output of the first command and copies it to the standard input. Roughly, pipe is an option to concatenate two/more commands.

Friday, December 28, 2012

Thursday, December 27, 2012

What are the ways to read contents of a file in Perl?

open (FH, "< io.txt") or die $!;
while(<FH>)
{
 print $_;
}
close(FH);

or

use Fcntl;

sysopen(FH, "io.txt", O_RDONLY) or die $!;
while(<FH>)
{
 print $_;
}
close(FH) || die "Couldn't close file properly.";

or

use IO::File;

my $FH = new IO::File("io.txt", "r") or die "could not open $filename : $!\n";
while ($line = $FH->getline())
{
   print $line;
}
$FH->close();