0

I have failed miserably to ask perl to "search in an array for the elements I'm interested at, write their names or write an NA if you don't find them".

For example, suppose that I'm looking for Orc, Troll and Elf in an array

    @creatures = qw/Troll Knight Elf Shrubbery Dragon Ni/;

How can I check for them and (my big problem) when not finding them writing and NA. In this example I would look for something like this:

    NA  Troll   Elf

Thanks

3 Answers 3

3

You can use a hash for quick lookup:

my %creatures = map { $_ => 1 } @creatures;

print $creatures{$_} ? $_ : "NA" for qw(Orc Troll Elf);

Note that this matches case sensitively, so it will consider "orc" and "Orc" two different things. You can solve this by converting to a specific case beforehand:

my %creatures = map { lc($_) => 1 } @creatures;

print $creatures{lc($_)} ? $_ : "NA" for qw(Orc Troll Elf);

You can also use grep:

for my $race (qw(Orc Troll Elf)) {
    if (grep /^$race$/i, @creatures) {
        print $race;
    } else {
        print "NA";
    }
}

Note the use of /i modifier to make the match case insensitive.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the Smart Match:

#!/usr/bin/perl
use warnings;
use strict;

my @creatures = qw/Troll Knight Elf Shrubbery Dragon Ni/;
my @searches  = qw/Orc Troll Elf/;

for my $search (@searches) {
    if ($search ~~ @creatures) {
        print $search, ' ';
    } else {
        print "NA ";
    }
}

Comments

0

With the basic knowledge of perl:

use warnings;
use strict;

my @str = qw(Troll Knight Elf Shrubbery Dragon Ni);
my %hash;
my @to_match = qw(Orc Troll Elf);
foreach my $s (@str) {
    $hash{$s} = $s;
}

foreach (@to_match) {
    if (defined $hash{$_}) {
        print "$_ ";
    } else {
        print "NA ";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.