Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: Array, element inside limits

by ikegami (Pope)
on Jun 15, 2009 at 17:40 UTC ( #771731=note: print w/ replies, xml ) Need Help??


in reply to Re: Array, element inside limits
in thread Array, element inside limits

my @ordered_result_list = sort keys %results;

That's wrong. You're sorting lexically, so 10 comes before 9.

print sort 1..10; # 1 10 2 3 4 5 6 7 8 9

The above is equivalent to

print sort { $a cmp $b } 1..10; # 1 10 2 3 4 5 6 7 8 9

You want to sort numerically.

print sort { $a <=> $b } 1..10; # 1 2 3 4 5 6 7 8 9 10

Of course, there's no reason to sort the result if you just want the highest.

use List::Util qw( max ); print max 1..10; # 10

my %results = map { $_ => 1 if ( $low_watermark < $_ && $_ < $high_wat +ermark ) } @all_numbers;

That's wrong. You're incorrectly assuming the expression in the map returns nothing when the condition is false.

$ perl -wle'my %h = map { $_ => 1 if $_ > 5; } 1..3; print 0+keys(%h); +' Odd number of elements in hash assignment at -e line 1. 1

You wanted:

my %results = map { if ( $low_watermark < $_ && $_ < $high_watermark ) + { $_ => 1 } else { () } } @all_numbers;

Or:

my %results = map { ( $low_watermark < $_ && $_ < $high_watermark ) ? +$_ => 1 : () } @all_numbers;

But why is a hash involved at all?

my @results = grep { $low_watermark < $_ && $_ < $high_watermark } @al +l_numbers; print max(@results), "\n";


Comment on Re^2: Array, element inside limits
Select or Download Code
Re^3: Array, element inside limits
by RMGir (Prior) on Jun 16, 2009 at 11:53 UTC
    For that matter, why use max, since the natol44 specified "a sorted array of numbers"?
    print $results[-1],"\n";
    :)

    Mike
      Good catch. Thanks.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://771731]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (14)
As of 2014-08-29 15:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (281 votes), past polls