代码之家  ›  专栏  ›  技术社区  ›  tavalendo

将字符串作为数组传递给子例程并返回特定字符的计数

  •  0
  • tavalendo  · 技术社区  · 6 年前

    -我想把n个元素数组作为参数传递给一个子例程。对于每个元素,匹配两种字符类型 S T 打印每个元素,这些字母的数量。到目前为止,我做到了这一点,但我被锁定,并发现一些无限循环在我的代码。

    严格使用; 使用警告;

    sub main {
    
    my @array = @_;
    
    while (@array) {
        my $s = ($_ = tr/S//);
        my $t = ($_ = tr/T//);
        print "ST are in total $s + $t\n";
        }
    }
    
    my @bunchOfdata = ("QQQRRRRSCCTTTS", "ZZZSTTKQSST", "ZBQLDKSSSS");
    main(@bunchOfdata);
    

    我希望输出为:

    Element 1 Counts of ST = 5
    Element 2 Counts of ST = 6
    Element 3 Counts of ST = 4
    

    你知道怎么解决这个问题吗?

    3 回复  |  直到 6 年前
        1
  •  7
  •   ikegami Gilles Quénot    6 年前

    对你的问题有几点意见。Perl程序很少定义 main() 作为一个sub,这是Python的方法。

    while (@array) 将是一个无限循环 @array 永远不会变小。无法读入默认变量 $_ 这种方式。要使其工作,请使用 for (@array) 将数组项读入 $_ 一次一个,直到全部读完。

    tr 音译运算符是执行任务的正确工具。

    获取结果所需的代码可以是:

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my @data = ("QQQRRRRSCCTTTS", "ZZZSTTKQSST", "ZBQLDKSSSS");
    
    my $i = 1;
    
    for (@data) {
        my $count = tr/ST//;
        print "Element $i Counts of ST = $count\n";
        $i++;
    }   
    

    另外,请注意 my $count = tr/ST//; $_ . Perl假设 $_ 保存要在此处计数的值。您的代码已尝试 my $s = ($_ = tr/S//); 这将给出结果,但我显示的较短的方式是首选的方式。

    (刚刚注意到你 = 而不是 =~ 在你的陈述中。那是个错误。必须是 $s = ($_ =~ tr/S//);

    你可以像我的代码一样把这两个字母组合起来。没有必要分开做。

    我得到了你想要的结果。

    Element 1 Counts of ST = 5
    Element 2 Counts of ST = 6
    Element 3 Counts of ST = 4
    

    而且,不能像以前那样在带引号的字符串中执行数学运算。

    print "ST are in total $s + $t\n";

    相反,您需要:

    print "ST are in total ", $s + $t, "\n";

    在字符串外部执行操作。

        2
  •  0
  •   Dave Cross    6 年前

    不要使用 while 遍历一个数组-你的数组不会变小,所以条件总是真的,你会得到一个无限循环。你应该使用 for foreach )相反。

    for (@array) {
      my $s = tr/S//; # No need for =~ as tr/// works on $_ by default
      my $t = tr/T//;
      print "ST are in total $s + $t\n";
    }
    
        3
  •  0
  •   ikegami Gilles Quénot    6 年前

    为什么? tr/// ??

    sub main {
        my @array = @_;
    
        while (@array) {
            my $s = split(/S/, $_, -1) - 1;
            my $t = split(/T/, $_, -1) - 1;
            print "ST are in total $s + $t\n";
        }
    }