my %countries = ( India => 1, America => 1, Germany => 1, Austria => 1, ); if ($countries{$country}){ print "$country is indeed a country\n"; }
Note that Perl 6 does support comparisons the way you wanted to do it, and they are called junctions. You could write that as
use v6; # ensure we run Perl 6 my $country = 'Foo' if $country eq 'America' | 'India' | ... { say "True" } # or if you want to use an array: my @countries = <America India Germany Austria>; if $country eq any(@countries) { say "True" }
Update: Here is a (perl 5) benchmark.
#!/usr/bin/perl use strict; use warnings; # get list of countries: open my $f, '<:encoding(UTF-8)', 'countries' or die "Can't read file: $!"; my @countries = <$f>; close $f; chomp @countries; for (@countries) { s/^([^;]+).*/\u\L$1/; } use Benchmark qw(cmpthese); use List::Util qw(first); my $re = join '|', map quotemeta, @countries; sub regex { die "regex" unless 'Germany' =~ m/^(?:$re)$/; die "regex" if ' Foo' =~ m/^(?:$re)$/; } sub mgrep { die "grep" unless grep { $_ eq 'Germany' } @countries; die "grep" if grep { $_ eq 'Foo' } @countries; } sub mfirst { die "grep" unless first { $_ eq 'Germany' } @countries; die "grep" if first { $_ eq 'Foo' } @countries; } my %hash = map { $_ => 1 } @countries; sub hash { die "hash" unless $hash{Germany}; die "hash" if $hash{Foo}; } cmpthese(-1, { regex => \®ex, grep => \&mgrep, first => \&mfirst, hash => \&hash, });
The file countries is the UT8-recoded part of the ISO list of country codes with stripped preamble. It's a list of 246 country names.
# perl 5.8.8: Rate grep first regex hash grep 8219/s -- -17% -72% -100% first 9863/s 20% -- -67% -100% regex 29805/s 263% 202% -- -99% hash 3682290/s 44701% 37233% 12255% -- # perl 5.10.0: Rate grep first regex hash grep 8532/s -- -21% -80% -100% first 10778/s 26% -- -75% -100% regex 43115/s 405% 300% -- -99% hash 3429921/s 40099% 31723% 7855% --
You can see that the trie optimization in 5.10.0 boost the performance of the regex method, but it doesn't change the overall order.
With Perl 5.10.0 and later you can also use smartmatching, which is quite fast:
sub smartmatch { die 'smart' unless 'Germany' ~~ @countries; die 'smart' if 'Foo' ~~ @countries; } __END__ Rate grep first smart regex hash grep 7587/s -- -17% -58% -83% -100% first 9135/s 20% -- -50% -79% -100% smart 18101/s 139% 98% -- -59% -99% regex 43840/s 478% 380% 142% -- -99% hash 3508785/s 46146% 38312% 19285% 7904% --
Oh, and I forgot to mention: TIMTOWTDI!
In reply to Re: Using the 'if' statement (with Benchmark)
by moritz
in thread Using the 'if' statement...
by rsriram
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |