Вопрос

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