Is there way to do something like this in perl?
$str = "A"
print "Yes" if $str in ('A','B','C','D');
Smart matching is experimental and will change or go away in a future release. You will get warnings for the same in Perl 5.18+ versions. Below are the alternatives:
Using grep
#!/usr/bin/perl
use strict;
use warnings;
my $str = "A";
print "Yes" if grep {$_ eq 'A'} qw(A B C D);
Using any
#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw(any);
print any { $_ eq 'A' } qw(A B C D);
Using hash
#!/usr/bin/perl
use strict;
use warnings;
my @array = qw(A B C D);
my %hash = map { $_ => 1 } @array;
foreach my $search (qw(A)) #enter list items to be searched here
{
print exists $hash{$search};
}
Also see:
You can transform your array to a hash. Then you can efficiently (in constant time, or O(1)) check if your string was in the original array. Here are two different approaches on how to look for the string 'C':
#!/usr/bin/perl
use strict;
use warnings;
my %hash1 = map {$_ => 0} qw/A B C D/;
print 'Yes' if exists $hash1{'C'};
#!/usr/bin/perl
use strict;
use warnings;
my %hash2;
@hash2{qw/A B C D/} = ();
print 'Yes' if exists $hash2{'C'};
But of course like always in Perl, TIMTOWTDI.
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