in reply to Quickly finding an element in an array

How about something like this:
#!/usr/bin/perl -wT use strict; my @arr = 1..10; my $tofind = 5; my $found; { grep {$_ == $tofind and $found = 1 and last} @arr; # wont get here if element is found; } print $found ? "I found" : "I didn't find", " element $tofind\n";

Update: changed eq to ==. Thanks to dvergin for the catch.
Update2: managed to munge my previous update... thanks to tomhukins for this catch.

-Blake

Replies are listed 'Best First'.
Re: Re: Quickly finding an element in an array
by tomhukins (Curate) on Jan 08, 2002 at 01:48 UTC

    Thanks, I've modified my code to use this, but surprisingly perl is dumping core (5.005_03 on FreeBSD and 5.6.1 on Solaris). This is a different problem, but I'm really surprised it's happening. Does anyone know why? Here's some code that reproduces the problem:

    #!/usr/bin/perl -Tw use strict; use Benchmark; my @array; foreach (1..1000) { push @array, 1 + int rand 199; } my @start = (0, @array); my @end = (@array, 0); my @middle = @array; splice(@middle, 500, 0, 0); timethese(1000, { 'grep_middle' => sub { my $found = 0; grep {$_ == 0 and $found = 1 and last} @middle; }, 'foreach_middle' => sub { my $found = 0; foreach (@middle) { $_ == 0 and $found = 1 and last; } }, 'hash_middle' => sub { my $found = 0; my %hash = map { $_ => undef } @middle; $found = 1 if exists $hash{0}; } });
      The bare block around the grep is important... Change this line:
      grep {$_ == 0 and $found = 1 and last} @middle;
      To:
      { grep {$_ == 0 and $found = 1 and last} @middle; }
      And I get:
      Benchmark: timing 1000 iterations of foreach_middle, grep_middle, hash +_middle... foreach_middle: 1 wallclock secs ( 0.80 usr + 0.00 sys = 0.80 CPU) +@ 1250.00/s (n=1000) grep_middle: 3 wallclock secs ( 3.09 usr + 0.00 sys = 3.09 CPU) @ 3 +23.62/s (n=1000) hash_middle: 30 wallclock secs (26.40 usr + 0.02 sys = 26.42 CPU) @ 3 +7.85/s (n=1000)

      -Blake