rahulme81 has asked for the wisdom of the Perl Monks concerning the following question:

I need to use array elements while pattern matching.

 @myarr = (ELEM-1, ELEM-2, ELEM-3,ITEM-1,ITEM-2,ITEM3);

ELEM-1, ELEM-2, ELEM-3,ITEM-1,ITEM-2,ITEM3 are the distinct column values from a file which I read in beginning of my scripts and store them in @myarr.

Basically What I intend to do is

1. If my @myarr = (ITEM-1,ITEM-2,ITEM3) ==> I print all the information from items.txt file.

2. If my @myarr = (ELEM-1, ELEM-2, ELEM-3) ==> I print all the information from elem.txt file.

3. If my @myarr = (ELEM-3,ITEM-1,ITEM-2,ITEM3)

==> I want to print all the information from items.txt file + Some few lines for elem.txt (Based on Pattern Match in file with keyword ELEM-3 in @myarr)

I am able to code the things for 1 and 2 but not not able to achieve my Point 3 If my @myarr = (ELEM-3,ITEM-1,ITEM-2,ITEM3)

I need a generic code instead of hardcoding the array elements inside the code since array elements are not known & may vary.

Thanks in advance.

Replies are listed 'Best First'.
Re: Perl:Use of array elements in pattern matching
by Laurent_R (Canon) on Aug 29, 2016 at 06:15 UTC
    What are your array items? Are they strings, or something else?

    What is the difference between an ITEM and an ELE, or how can we tell what they are?

Re: Perl:Use of array elements in pattern matching
by Anonymous Monk on Aug 29, 2016 at 04:21 UTC

    I am able to code the things for 1 and 2 but not not able to achieve my Point 3 If my @myarr = (ELEM-3,ITEM-1,ITEM-2,ITEM3)

    Why not? Can you show what you have so far?

      Below is snippet what I have tried so far

      # this is called in foreach loop and stores returns the file in array for elem and item.

       my $ref_to_elem_entries = myfunction($itend_file);

      # This is the pattern which I look for in elem.txt if @myarr = "ELEM-3"

      my @intend_elem = (win,won,wion,wiin,woon,wiioon); foreach my $itend_elem (@intend_elem) { if ($ask =~ /^SA/ && (@myarr ==1 && $myarr[0] eq 'ELEM-3')) {push @m_ref_to_elem_entries, grep(/^reg\b/,@$ref_to_elem_entries) } else {@m_ref_to_elem_entries = @$ref_to_elem_entries} }

      With above piece of code If condition gives me only lines for ELEM-3 and lines which has pattern stored in @intend_elem.

      Else condition gives me all lines for Item & Elem files.

      So far - if @myarr contains only ELEM-3 I have my result else I have results for all.

        Hi,

        Does this give you any ideas? Questions?

        itemElemIt( '...items.txt', '...elem.txt', \@myarr ); sub itemElemenIt { my( $itemfile, $elemfile, $myarr ) = @_; for my $lookFor ( @$myarr ){ ... lookIn( $itemfile, $lookFor ); } } sub lookIn { my( $file, $keyword ) = @_; my @ret; while(<$fh>){ push @ret, $_ if /\Q$keyword\E/; } return @ret; }