On 8/31/2011 3:27 PM, Vaishak S wrote:
> Hi Luebkert and Martin,
>
>
> In the code I wanted to have the hash names to be used as the files names in
> the array... , the challenge here is for loading the text file data to
> different hashes.
>
> the hash name should be hash_A.txt for the A.txt file and hash_B.txt for the
> B.txt file
> Also I need to call these hash_A.txt file afterwards.
> Not sure if this is possible.
> $hash{$server}{location} = $location; # the hash name should
> be hash_A.txt for the A.txt file and hash_B.txt for the B.txt file
> $hash{$server}{ip} = $ip; # the hash name should be
> hash_A.txt for the A.txt file and hash_B.txt for the B.txt file
hash_A.txt is not a legal symbol/name for a hash. I have no idea
why you're trying to do what you are doing - why not explain why
you're doing or what you want to accomplish rather than insisting
on using dynamic naming of hashes.
You could try something like this instead:
use strict;
use warnings;
use Data::Dumper; $Data::Dumper::Indent=1; $Data::Dumper::Sortkeys=1;
# these text files are in csv format
# servername,location,ipaddress from where app is accessed
# my @array = ("A.txt", "B.txt", "C.txt");
my @array = ('A', 'B', 'C');
my %hash_A = (); # hash for group A
my %hash_B = ();
my %hash_C = ();
my $href; # href will point to one of above group hashes at a time
foreach my $file (@array) {
eval "\$href = \\%hash_$file"; # point to right hash
# open the corresponding file (I have them in data dir below me)
open IN, "data/$file.txt" or die "open $file.txt: $! ($^E)";
while (<IN>) {
chomp;
next if /\s*#/;
my ($server, $location, $ip) = split /\s*,\s*/;
if (exists $href->{$server}) {
print "Skipping dup server $server in file $file\n";
next;
}
$href->{$server}{location} = $location;
$href->{$server}{ip} = $ip;
}
close IN;
}
# print (Data::Dumper->Dump([\%hash_A], [qw(%hash_A)])); # see how your hash
looks
# print (Data::Dumper->Dump([\%hash_B], [qw(%hash_B)]));
# print (Data::Dumper->Dump([\%hash_C], [qw(%hash_C)]));
# print out hash for 'A' group
foreach (sort keys %hash_A) {
printf "%s => location='%s', ip='%s'\n", $_,
$hash_A{$_}{location}, $hash_A{$_}{ip};
}
# ...
__END__
output:
server1 => location='location1', ip='1.2.3.4'
server2 => location='location2', ip='1.2.3.5'
server3 => location='location3', ip='1.2.3.6'
server4 => location='location4', ip='1.2.3.7'
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs