Re: undif as if it is 0
From: Bob Walton (invalid-email_at_rochester.rr.com)
Date: 11/25/03
- Next message: Edo: "Re: push @arr, slice-of-href"
- Previous message: Gunnar Hjalmarsson: "Re: push @arr, slice-of-href"
- In reply to: Edo: "undif as if it is 0"
- Next in thread: Edo: "Re: undif as if it is 0"
- Reply: Edo: "Re: undif as if it is 0"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 25 Nov 2003 04:14:16 GMT
Edo wrote:
...
> I am getting $max = undif if nothing in @top3, but due to the way the
undef?----------------^^^^^
> code below is written, I need it to show 0 instead.
> do I have to change the code? or there is an operator to change undif to
> 0 in this case?
...
> my @kd = keys %$dbits; my @ks = keys %$sbits;
> my @vs = @$sbits{ @ks };
>
> for( 0 .. 5 ) {
> my $tmp = 4;
> my $max = (sort {$b <=> $a} @top3)[0];
> if ( $tmp > $max ) {
> ... code
> push @top3, \%set;
> }
> }
>
Unless you need the contents of $max for something else not shown, it
will not matter if $max is 0 or undef. Since > is a numeric comparison
operator, undef will be treated the same as 0 in the comparison, and you
don't use $max elsewhere. If you really need it to be a numeric 0, put:
$max+=0;
after the sort. That will force a "numerification" of $max, and will be
a no-op if $max is already numeric. Or append +0 to the end of the
sort, as in:
my $max = (sort {$b <=> $a} @top3)[0]+0;
Also, I note that you are pushing references to the hash %set to the
array @top3, which is the same array you are sorting on. There are two
things wrong here: First, the next time through your for loop, you will
sort this hash reference numerically with whatever was already in @top3,
and then compare the largest of the result with $max. That is not a
reasonable thing to do with references. What it is you are really
trying to accomplish? The second problem is (although you haven't shown
where hash %set is defined), you may be pushing references to *the same
hash* into @top3 time after time. If so, all the references will then
point to *the same hash*, the one called %set, and you'll wonder why you
have an array full of references to the same hash over and over. This
is a very common bug, and one that can be a bit tricky to ferret out.
You should probably push a reference to an anonymous copy of your hash,
as in:
push @top3,{%set};
BTW, please improve your indenting style. The lack of reasonable
indenting makes your program harder to follow than necessary. Thanks.
-- Bob Walton Email: http://bwalton.com/cgi-bin/emailbob.pl
- Next message: Edo: "Re: push @arr, slice-of-href"
- Previous message: Gunnar Hjalmarsson: "Re: push @arr, slice-of-href"
- In reply to: Edo: "undif as if it is 0"
- Next in thread: Edo: "Re: undif as if it is 0"
- Reply: Edo: "Re: undif as if it is 0"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|