0

I have a global array containing elements such as:

@myarray = ("A","B","C","D","E");

I'm reading a column line by line which has values like:

Row1: A
Row2: Z
Row3: B C
Row4: A B C
Row5: A B C Z
Row6: A C
Row7: E
  1. Problem 1 : If Row1 is read and has "A" which is present in @myarray -> no action required, but in case of Row2 "Z" is not a part of @myarray it should fail with some message.
  2. Some rows have multiple elements, it should check for all, for example row3 "A","B","C" all three are part of @myarray --> no action required, but incase of Row4 it should read "A" , "B","C", then comes "Z" which is not a valid element it should fail with some message.
1
  • 1
    Please show us your code. Needs minimal example Commented Jul 19, 2020 at 9:26

2 Answers 2

2

First, create a hash so we can easily and efficiently lookup if a value is valid.

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

Then, it's just a question of checking if all the values are in the hash.

while (<>) {
   my ($hdr, $values) = /^([^:]+):\s*(.*)/
      or do {
         warn("Invalid input at \"$ARGV\" line $.\n");
         next;
      };

   my @values = split(' ', $values);
   if ( my @invalid = grep { !$ok{$_} } @values ) {
      warn("Invalid values (@invalid) for $hdr at \"$ARGV\" line $.\n");
      next;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

See if this could help you.

#!/usr/bin/perl

use strict;
use warnings;
use List::Util qw(any);

my @array = qw/A B C D E/;

while(<DATA>){
    chomp($_);
    print "At line -> $_\n";
    my @contents = split(' ', $_);
    
    foreach my $each_element (@contents){
        if (not (any { $_ eq $each_element } @array)) {
            print "$each_element -> Not exists in array\n";
        }
    }
}

__DATA__
A
Z
B C
A B C
A B C Z
A C
E

As suggested by @ikegami, this could also work as per the expectation:

...
my @array = qw/A B C D E/;

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

while(<DATA>){
    chomp($_);
    print "At line -> $_\n";
    my @contents = split(' ', $_);
    
    foreach my $each_element (@contents){
        if (not ($skip_hash{$each_element})) {
            print "$each_element -> Not exists in array\n";
        }
    }
}

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.