hashes

bsd_linux
bsd_linux used Ask the Experts™
on
Hi,

I would appreciate if someone could tell me what is going wrong in this program.

I have a file which has enteries like

adfdsfa   100.000.000.0000

and no 2 enteries are same.

I am attempting to build a hash with the first field as a key and the second field as value. For some reason the program I wrote doesn't work. It just prints only the first line. I would appreciate if someone could point out the mistake.

Thanks

the code.

!/usr/bin/perl -w

use strict;
# defining the file name

my ($file_name) = 'fam.txt' ;

# Opening the file

if(!(open(file_handle, $file_name)))
{
    print "\n Error unable to open file \n";
    exit;
} else {
    print "\n File open success \n";
}

# declaring a hash
my(%hash) = ();

# Reading a line from the file
while (my($line) = <file_handle>)
{
my(@temp) = split(" ", $line);

$hash{$temp[0]} = "$temp[1]";
}


# if i define the loop as foreach my($val) it reports
# missing $.
my($val);

foreach $val (keys %hash) {
    print "\n $val ";
}

exit;


Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Your problem is in while() loop where you read lines of file, it should be:

my $line;
while($line = <file_handle>){
.... etc

and not:

while(my($line) = <file_handle>){
... etc

because you declare variable $line again for every loop, i.e. every line of your file. Just put my declaration out of while loop.
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
while( my $line=<> ){ # no () around $line
    my(@temp) = split(" ", $line);
    $hash{$temp[0]} = $temp[1];
}
Most Valuable Expert 2014
Top Expert 2015
Commented:
while( my $line=<file_handle> ){ # no () around $line, ($line) reads in list mode
    my(@temp) = split(" ", $line);
    $hash{$temp[0]} = $temp[1];
}
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

Author

Commented:
ozo :Sorry I did not quite follow why ($line) is reading in list mode. could you please elaborate.  by the way removing the paranthesis works

regards
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
@array = <file_handle>;  #reads all lines of the file
($line1,$line2) = @array; #gets the first two elements of @array
($line) = @array; #gets the first element of @array
($line) = <file_handle>; #reads the entire file, then puts the first element of the array into $file

Author

Commented:
ozo :Sorry I did not quite follow why ($line) is reading in list mode. could you please elaborate.  by the way removing the paranthesis works

regards

Author

Commented:
oops sorry the second comment was a mistake

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial