문제

I am trying to grep tab separated numbers (eg 1\t3) in an array something like

@data= 
1 3
2 3
1 3
3 3

the idea behind the code is something like this

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

   my @data = ( "1\t3", "2\t3", "1\t3", "3\t3", );
    for (my $i=0;$i<4;$i++) {
        for (my $j=0;$j<4_size;$j++) {
        my $pattern= "$i\t$j";
        my @count=grep(/$pattern/,@data); 
        undef $pattern;
        print "$pattern\tcount\n";
        }
        }

hoping for output something like

1st and second column: pattern

3nd column : count of total matches

1 1
1 2
1 3 2
2 1
2 3 1
3 1 
3 2
3 3 1

but the output is null for some reasons, I am recently learnt and finding it very intriguing. any suggestions?

도움이 되었습니까?

해결책 2

You almost got it. Here is a working version:

#!usr/bin/perl

use strict;
use warnings;

my @data = ( "1\t3", "2\t3", "1\t3", "3\t3", );

foreach my $i (1 .. 3) {
    foreach my $j (1 .. 3) {
        my $pattern = "$i\t$j";
        my $count = grep(/$pattern/, @data);
        print $pattern . ($count ? "\t$count\n" : "\n");
    }
}

다른 팁

The code below:

  1. Does not crash if input contains unexpected characters (e.g., '(')
  2. Only counts exact matches for the sequences of digits on either side of "\t".
  3. Matches lines that might have been read from a file or __DATA__ section without using chomp using \R.

--

 #!/usr/bin/env perl

 use strict;
 use warnings;

 my @data = ( "1\t3", "2\t3", "(\t4", "1\t3", "3\t3", "11\t3" );

 for my $i (1 .. 3) {
     for my $j (1 .. 3) {
         my $pattern = "$i\t$j";
         my $count = grep  /\A\Q$pattern\E\R?\z/, @data;
         print join("\t", $pattern, $count ? $count : ''), "\n";
     }
 }

Output:

1   1
1   2
1   3   2
2   1
2   2
2   3   1
3   1
3   2
3   3   1
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top