Thursday, June 12, 2008

PERL - Hash, Hash reference and file handler passing to a subroutines

Fews days ago - One of my friends asked me about:
1. hashes in perl
2. hash references and how to use them
3. file handler passing to a subroutines....

Here is an example.....


#!/opt/local/bin/perl

use warnings;
use strict;

my $n_ref;
my $p_ref;


open(NAME, "./tns_names") or die " Failed to open tns_names file : $! \n ";
open(PASS, "./tns_pass") or die " Failed to open tns_pass file : $! \n ";

$n_ref = &process_names(*NAME);
$p_ref = &process_pass(*PASS);

&do_final($n_ref, $p_ref);

close NAME;
close PASS;


sub process_names($)
{
local *h = shift;

my %n;
my $nkey;
my $nval;

while()
{
chomp $_;
($nkey, $nval) = split(/,/, $_);
$n{$nkey} = $nval;
}
return \%n;
}


sub process_pass($)
{
local *h = shift;

my %p;
my $pkey;
my $pval;

while()
{
chomp $_;
($pkey, $pval) = split(/,/, $_);
$p{$pkey} = $pval;
}
return \%p;
}


sub do_final(@)
{
my ($nam, $pas) = @_;
my $akey;

foreach $akey (keys %$nam)
{
print 'Key :' . $akey . ' and Value: ' . $nam->{$akey} . "\n";
}

foreach $akey (keys %$pas)
{
print 'Key :' . $akey . ' and Value: ' . $pas->{$akey} . "\n";
}
}


1;

No comments: