Question:

How would I manipulate numbers within a perl hash?

by  |  earlier

0 LIKES UnLike

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 LIST\n\n";

my %information = (total => 0,

male => 0,

female => 0,

outof => 0,

other => 0,

over => 0,

under => 0);

while (<SRECORD>) {

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?

 Tags:

   Report

2 ANSWERS


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

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

    %myhash = (&#039;foo&#039; =&gt; 1, &#039;bar&#039; =&gt; 2);

    But that&#039;s EXACTLY the same as if you did:

    %myhash = (&#039;foo&#039;,1,&#039;bar&#039;,2);

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

    $myhash{&#039;key&#039;}

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

    $myhash{&#039;key&#039;} = 5; #this is correct

    $myhash{&#039;key&#039;} =&gt; 5; #this is wrong

    $myhash{&#039;key&#039;} =&gt; &#039;key&#039; + 5; #this is even more wrong!

    So you can do one of:

    $myhash{&#039;key&#039;} = $myhash{&#039;key&#039;} + 1;

    $myhash{&#039;key&#039;}++;

    $myhash{&#039;key&#039;} += 1;

    What you&#039;ve actually got there is evaluating it as:

    $information{&#039;total&#039;} , &#039;total&#039; + 1; #this effectively does nothing

    $information{&#039;total&#039;} = &gt; &#039;total&#039; + 1; #this should be a parse error

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

    DaveE


  2. The body of your if statement is gibberish 8-)  Try this:

    $information{total}++;

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions