in reply to Re^2: Open a file and put the contents in a hash with a value
in thread Open a file and put the contents in a hash with a value
That's generally not such a great idea, even if you avoid the badness of having spaces in hash keys. Smashing strings together loses information that you may need later - e.g., you won't know if user "johara" used to be "jo hara" or "j ohara" (contrived, but you see the point.) Once you learn about references, you might want to consider a list of hashes (LoH) or a hash of hashes (HoH) to keep track of this kind of thing - e.g., "$user[0]->{Perry}{Steve} = 234" or "$user{0}{Perry}{Steve} = 234". That way, even if you get another "Perry, Steve", his unique number will keep him distinct from the previous one.
...but I'm wandering far afield. :) If you've just absolutely gotta do it the way you're describing, then at least separate the chunks with a delimiter that's not likely to occur in them - e.g., an underscore. My version of your script follows, with suggested modifications.
#!/usr/bin/perl use strict; use warnings; # Might as well declare this early on and save some typing :) my $s = "students.txt"; # *Always* check system operations for errors open Fh, ">", $s or die "$s: $!\n"; print Fh "Perry*Steve*234\nSmith*Jane*456\nJones*Mary*567\n"; close Fh; my (@bits, %pass); # Don't guess at the error ahead of time - get the real story with '$! +' open Fh, "<", $s or die "$s: $!\n"; while(<Fh>) { @bits = split /\*/; $pass{join "_", @bits[0,1]} = $bits[2]; } # Let's see what we got in the hash printf "%s:\t%d\n", $_, $pass{$_} for sort keys %pass;
-- Human history becomes more and more a race between education and catastrophe. -- HG Wells
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Open a file and put the contents in a hash with a value
by trenchwar (Beadle) on Apr 12, 2008 at 18:13 UTC |