【问题标题】:Perl: assignment within scalar and string matching (regex)Perl:标量和字符串匹配中的赋值(正则表达式)
【发布时间】:2021-02-10 21:48:48
【问题描述】:

我了解以下代码的一般目的(即总结字符串的数字部分,例如对于 currstr="3S47M" 然后 seqlength=50)。

但是有人可以逐行解释我发生了什么吗?

特别是,我很难理解where 在每个回合中所持有的价值。更准确地说,我不理解 scalar 函数 ("scalar($RLENGTH = length($&), $RSTART = length($`)+1)") 的部分?

RLENGTHRSTART的赋值发生在scalar内部是否正确?

为什么在 scalar 中使用逗号分隔的赋值?这是什么意思 ?那么它的评估结果是什么?

如果有人能提供帮助,我将非常感激!

谢谢

艾丽卡

  my $seqlength=0; 
  my $currstr="3S47M";

  my $where = $currstr =~ /[0-9]+[M|D|N|X|=|S|H|N]/
    ? scalar($RLENGTH = length($&), $RSTART = length($`)+1) : 0;
  while ($where > 0) {
    $seqlength += substr($currstr, ($where)-1, $RLENGTH - 1) + 0;
    $currstr = substr($currstr, ($where + $RLENGTH)-1);
    $where = $currstr =~ /[0-9]+[M|D|N|X|=|S|H|N]/
      ? scalar($RLENGTH = length($&), $RSTART = length($`)+1) : 0;
  }

编辑:RSTART 的目的是什么?为什么写scalar($RLENGTH = length($&)不起作用?

【问题讨论】:

    标签: regex perl scalar


    【解决方案1】:
    $where = $currstr =~ /[0-9]+[M|D|N|X|=|S|H|N]/
      ? scalar($RLENGTH = length($&), $RSTART = length($`)+1) : 0;
    

    等价于

    if ($currstr =~ /[0-9]+[M|D|N|X|=|S|H|N]/) {
       $where = scalar($RLENGTH = length($&), $RSTART = length($`)+1);
    } else {
       $where =  0;
    }
    

    scalar 在这里没用。表达式已经在标量上下文中。简单的括号就可以了。

    EXPRX, EXPRY 在标量上下文中求值时,EXPRXEXPRY 会依次求值,结果为EXPRY。因此,以上等价于

    if ($currstr =~ /[0-9]+[M|D|N|X|=|S|H|N]/) {
       $RLENGTH = length($&);
       $RSTART = length($`) + 1;
       $where = $RSTART;
    } else {
       $where =  0;
    }
    

    注意[M|D|N|X|=|S|H|N][MDX=SHN|] 的一种奇怪的写法。重复的 N| 将被忽略。事实上,| 可能根本不应该存在。我怀疑应该是[DHMNSX=]


    如果我理解正确,代码可以写成如下:

    my $currstr = "3S47M";
    
    my $seqlength = 0; 
    while ($currstr =~ /([0-9]+)[DHMNSX=]/g) {
       $seqlength += $1;
    }
    

    以下内容甚至可能就足够了(尽管不是等效的):

    my $currstr = "3S47M";
    
    my $seqlength = 0; 
    while ($currstr =~ /[0-9]+/g) {
       $seqlength += $&;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 2021-07-28
      • 2021-09-11
      • 2014-08-06
      相关资源
      最近更新 更多