in reply to Re: Pop quiz: find the bug
in thread Pop quiz: find the bug

if (defined $total {$id}) { $total {$id} += $amt; } else { $total {tocredit} += $amt; }
Nice article, and a nice piece of code. However, there's still something in this piece of code that can be factored out.
$total {exists $total {$id} ? $id : "tocredit"} += $amt;
Or, in a more ALGOLish style:
(exists $total {$id} ? $total {$id} : $total {tocredit}) += $amt;
Note also the use of exists instead of defined; when using exists, we avoid having to initialize all the entries in the hash.

Abigail

Replies are listed 'Best First'.
Re: Re: Pop quiz: find the bug
by jjohn (Beadle) on Jul 05, 2002 at 05:59 UTC

    Note also the use of exists instead of defined; when using exists, we avoid having to initialize all the entries in the hash.

    Originally, I thought exists was the correct operator and indeed it would be given your assumption that only keys with values need to be inserted into the hash. Since I'm a simple and lazy guy, I thought that the values would all be retrieved from an SQL table. If so, the most naive way to handle row data is simply to retrieve the data as a hash. The method of populating the %total hash is pure speculation on my part and surely one could carefully create the hash so that only those keys with values would be inserted. In this case (your case), your solution is superior. Your code may be a little terse for some (although I find the second form of your solution titillating -- using the trigraph operator to select the lvalue is uncommon (because I've never used ALGOL)).

    Thank you for your kind words about my post, but be advised that you are only encouraging me to post more. ;-)

      using the trigraph operator to select the lvalue is uncommon (because I've never used ALGOL))
      As far as I know, ALGOL didn't have the trigraph operator; it actually has a way cooler way of selecting an lvalue - lvalues could be the return value of an IF statement. So, you could do something like:
      IF var1 THEN var2; ELSE var3; FI := IF var4 THEN var5; ELSE var6; FI;
      I can't remember the details of ALGOL syntax, so it could very well be the above code is missing semi-colons or parenthesis somewhere.

      Abigail