in reply to Counting Array in an Array of HoA

you can use this:

#!/usr/bin/perl -w use strict; use Data::Dumper; # While matching the hash, elem of each array must occur together # and in order my @ar1 = ('A','B'); #Answer: 3 my @ar2 = ('B','A'); #Answer: 1 my @ar3 = ('A','B','C'); #Answer: 2 my $hash = { 'S1' => [ 'A', 'B', 'C', 'A' ], 'S2' => [ 'A', 'C', 'D', 'B' ], 'S3' => [ 'C', 'A', 'D', 'H' ], 'S4' => [ 'A', 'B', 'I', 'C' ] }; count_($hash,\@ar1); count_($hash,\@ar2); sub count_ { my ($hashref,$arref) = @_; my $counter = 0; my $test = join('.*?',@$arref); print "Query: ",join('',@$arref),"\n"; for my $key(sort{$a cmp $b}keys(%$hashref)){ my $string = join('',@{$hashref->{$key}}); print $string," - "; if($string =~ $test){ print "1\n"; $counter++; } else{ print "0\n"; } } print "Total counter: ",$counter,"\n" }# end count_


output:
Query: AB ABCA - 1 ACDB - 1 CADH - 0 ABIC - 1 Total counter: 3 Query: BA ABCA - 1 ACDB - 0 CADH - 0 ABIC - 0 Total counter: 1

Replies are listed 'Best First'.
Re^2: Counting Array in an Array of HoA
by monkfan (Curate) on May 09, 2005 at 14:13 UTC
    reneeb,
    Thanks so much for your reply. I wonder what do these two lines do?
    my $test = join('.*?',@$arref); $string =~ $test # this is the first time # I see "=~" used in non-regex context # what's the purpose?
    Regards,
    Edward
      No, I believe the "=~" is used in regex there, from my minimal understanding $test is the string that contains the regex. I am still trying to understand the how on the rest of the script, though.

      Update: After some testing, I used a much simpler version to get to this.
      #!/usr/bin/perl -w use strict; my $string='ABCD'; my $string1='DCBA'; my $test='.*?AB'; print "Matched in $string" if $string =~ $test; # Prints Match. print "Matched in $string1" if $string1 =~ $test; # Does not print + Match.

      So $test does contain the regex '.*?AB' or '.*?BA'. If I am not correct here, please let me know.

      Update: Adjusted code to differentiate the output.