The best way to convert the array to hash is unclear without seeing what it was used for earlier in the code - map (above) is only one way to process the array and the assumption anyway is that you are reusing the list and can in the exact situation benefit from paying some fixed overhead in return for variable cost-reduction, otherwise the cost of making a hash is probably greater than a single pass through the list. This point is somewhat influenced by the surprisingly-overlooked fact that the single pass approach can on average execute only half the duration for a one-off pass by aborting when it succeeds, e.g.my %hash = (); my $dummy = map( $hash{ $_ } = 1, @array ); my $checkthis = 'at'; ... if ( defined( $hash{ $checkthis )) { ... }
whereas in the first example, the array has to be passed right through plus the hash setup costs in order to make future lookups cheaper - I would estimate the reuse count to be about 4 - 6 to break even on the deal, with more uses profiting and less losing.my $found = ( $_ eq $checkthis ) && last for ( @array );
Update 1: rephrased - I did not mean to imply that the bug always happens.
Update 2 BUT, in actual work I always use the arrow operator (under which conditions the bug with exists would apply) and therefore never use exists - this kind of thing is unavoidably common in occurrence:
the only reason I would need to use exists instead of defined is if I have a habit of defining keys with a value equal to undef(). Instead I have a habit of not defining the key.use strict; use warnings; Package Company; sub new { my $self = shift; my $regno = shift or die "Must supply reg. no."; $self = {}; $self -> { REGNO } = $regno; return bless $self; } sub parent { my $self = shift; my $parent; unless ( $parent = shift() ) { if (defined $self -> { PARENT } ) { return $self -> { PARENT }; else { return undef(); } } if ( defined $parent -> { REGNO } ) { $self -> { PARENT } = $parent; } else { die "Invalid parent reference"; }
-M
Free your mind
In reply to Re^2: searching a list
by Moron
in thread searching a list
by keiusui
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |