Your Questions About: Hash Equals

Posted by | By | Reply More

Lisa asks…

How would I manipulate numbers within a perl hash?

I don’t know why I would *ever* do this, I could do it just as well with scalars and arrays, but *sigh*, this course I’m in requires it.

open SRECORD, “srecord.txt” or die “Cannot open srecord.txt: $!”;

print “STUDENT LISTnn”;
my %information = (total => 0,
male => 0,
female => 0,
outof => 0,
other => 0,
over => 0,
under => 0);
while () {
chomp;
my $record = substr($_, 0 ,1);
if ($record eq ‘U’) {$information{‘total’} => ‘total’ + 1;}
if ($record eq ‘S’) {
$information{‘total’} = >’total’ + 1;

That’s a snippet of the code… But when I print the hash, “total” always equals 1. What am I doing wrong?

Potter answers:

Your assignment statements are wrong. I can see what you’re trying to do, but how it’s actually getting processed is strange.

You’re assuming (apparently) that using the ‘=>’ syntax will assign values to your hash, but that’s not really the case. In Perl, the ‘=>’ operator is exactly equivalent to a comma. So when you define a hash, you may see:

%myhash = (‘foo’ => 1, ‘bar’ => 2);

But that’s EXACTLY the same as if you did:

%myhash = (‘foo’,1,’bar’,2);

The way to access a hash value is as you correctly typed into the left side of your assignment statement:

$myhash{‘key’}

However, you assign them just like you would any other variable:

$myhash{‘key’} = 5; #this is correct
$myhash{‘key’} => 5; #this is wrong
$myhash{‘key’} => ‘key’ + 5; #this is even more wrong!

So you can do one of:

$myhash{‘key’} = $myhash{‘key’} + 1;
$myhash{‘key’}++;
$myhash{‘key’} += 1;

What you’ve actually got there is evaluating it as:

$information{‘total’} , ‘total’ + 1; #this effectively does nothing
$information{‘total’} = > ‘total’ + 1; #this should be a parse error

In fact, I’m not sure why you’d get a value of 1 at all– it should always give you a null value for $information{‘total’}! I’m assuming you’ve got some more code elsewhere that’s setting it equal to 1.

DaveE

Powered by Yahoo! Answers

Category: FAQs

Comment Via Your Facebook Profile Below - or by Regular Blog Comment Farther Below ( scroll down a bit!):

Leave a Reply