Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Constructing a hash

by Anonymous Monk
on Mar 17, 2011 at 07:27 UTC ( #893681=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to construct a hash like below,i dont see any errors but I dont see the hash getting constructed?Any idea?
use warnings; use strict; open (my $fh, '<', "data.txt") or die "could not open dirs.log $!; while (my $line=<$fh>) { $key = lc($line); $Hash{$key}=$line; } open my $hash, '>', "hash.txt"; print $hash Dumper( \%Hash ); close $hash;

Replies are listed 'Best First'.
Re: Constructing a hash
by bart (Canon) on Mar 17, 2011 at 08:12 UTC
    You didn't declare all the variables: %Hash, $key. Your error message on line 3 is missing the closing quote. You didn't use Data::Dumper (for Dumper). Check the return value (and $! if it fails) of the second open call.

    And then, at least, you should see an error message, or a file with at least an empty hash in it.

    Oh, and you probably want to chomp each line.

    Is there a reason why you're not seeing existing error messages, for example for the current failed compilation? Because that's what it looks like to me.

Re: Constructing a hash
by philipbailey (Deacon) on Mar 17, 2011 at 08:16 UTC

    Your program doesn't run as shown, so you have either retyped it incorrectly or are mistaken in thinking you have run it. It is always best to cut and paste the exact program you are trying to debug.

    Once the missing shebang line, missing closing double quote in the die, missing use statement for Data::Dumper, and missing declaration of variables are all fixed, the program in fact works.

Re: Constructing a hash
by Anonymous Monk on Mar 17, 2011 at 07:36 UTC
    Your program does not compile or run as is (it will die with errors), so maybe you're not running the program at all?

      Can someone help me constructing the hash?

Re: Constructing a hash
by danwoods (Initiate) on Mar 17, 2011 at 15:02 UTC
    Yeah, like the other people said, your code has some serious fundamental problems... May need to hit an intro to perl tutorial or something... But, for now:
    use strict; use warnings; use Data::Dumper; open (FH, "<data.txt"); my (%hash); while (my $line = <FH>) { my $key = lc($line); $hash{$key} = $line; } close(FH); open (FH, ">hash.txt"); print FH Data::Dumper->Dump([%hash]); close(FH);
    That should work for you.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://893681]
Approved by chrestomanci
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2022-05-26 13:30 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (93 votes). Check out past polls.