my %countries = (
India => 1,
America => 1,
Germany => 1,
Austria => 1,
);
if ($countries{$country}){
print "$country is indeed a country\n";
}
####
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 = ;
if $country eq any(@countries) {
say "True"
}
####
#!/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,
});
####
# 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% --
####
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% --