This function does the same as exists
does with hashes.
I plan on use it a lot.
Can it be optimized in some way?
my @a = qw/a b c d/;
my $ret = array_exists("b", @a);
sub array_exists {
my ($var, @a) = @_;
foreach my $e (@a) {
if ($var eq $e) {
return 1;
}
}
return 0;
}
In case of multiple iterations of the loop, and where the size of array is too large, for loop is the preference as the fastest method of elements' iteration. While loops perform efficient scaling in case of large arrays. In case of functional codes, for each loop performs better with a much optimized time.
Conclusions. List comprehensions are often not only more readable but also faster than using “for loops.” They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.
If you have to do this a lot on a fixed array, use a hash instead:
my %hash = map { $_, 1 } @array;
if( exists $hash{$key} ) { ... }
Some people reach for the smart match operator, but that's one of the features that we need to remove from Perl. You need to decide if this should match, where the array hold an array reference that has a hash reference with the key b
:
use 5.010;
my @a = (
qw(x y z),
[ { 'b' => 1 } ],
);
say 'Matches' if "b" ~~ @a; # This matches
Since the smart match is recursive, if keeps going down into data structures. I write about some of this in Rethinking smart matching.
You can use smart matching, available in Perl 5.10 and later:
if ("b" ~~ @a) {
# "b" exists in @a
}
This should be much faster than a function call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With