如何在Perl中用新字符串替换最后一个字符串字符

时间:2020-03-25 20:28:43

标签: perl substr

我正在B列中迭代一个excel工作表。如果一个单元格包含一个",则将其替换为Inches。但是,使用substr函数时,$newval保持空白。在测试运行中,$cell$ind都包含正确的值。我没有错误,也没有警告。

为什么$newval为空白?我在网上找到了这个substr-example,似乎无法弄清楚我在做什么:

使用substr作为左值的另一种方法是将替换字符串指定为第4个参数。这样一来,您就可以像替换拼接一样替换EXPR的各个部分,并返回以前的操作。

    my $s = "The black cat climbed the green tree";
    my $z = substr $s, 14, 7, "jumped from";    # climbed
    # $s is now "The black cat jumped from the green tree"

这是我的代码:

    ...

    if($sheet->Range("B". $i)->{Value} =~ m/\"/)
    {
                    my $cell = $sheet->Range("B". $i)->{Value};
                    print $cell . "\n"; # Notebook 24"
                    my $ind = index($cell, '\"');
                    print $ind ."\n";   # -1                        
                    my $newval = substr($cell, $ind, 0, " Inches");
                    print $newval . "\n"; # (blank)
                    <STDIN>;
                    $sheet->Range("B". $i)->{Value} = $newval;                      
    }

    ...

编辑:(在控制台中添加了示例输出) enter image description here

编辑2 :(索引现在是正确的且正确的)

...

if($sheet->Range("B". $i)->{Value} =~ m/\"/)
{
                my $cell = $sheet->Range("B". $i)->{Value};
                print $cell . "\n"; # Notebook 24"
                my $ind = index($cell, '"');
                print $ind ."\n";  # 11                       
                my $newval = substr($cell, $ind, 0, " Inches");
                print $newval . "\n"; # (blank)
                <STDIN>;
                $sheet->Range("B". $i)->{Value} = $newval;                       
}

...

控制台输出:

enter image description here

2 个答案:

答案 0 :(得分:3)

双引号在单引号中不需要反斜杠。

index($cell, '\"');

相反:它搜索反斜杠后跟双引号,该字符串中不存在双引号,因此返回值为-1。

say index 'Notebook 24"', '\"';  # -1
say index 'Notebook 24"', '"';   # 11

答案 1 :(得分:0)

解决方案:

...

if($sheet->Range("B". $i)->{Value} =~ m/\"/)
{                   
   $sheet->Range("B". $i)->{Value} =~ s/"/ Inches/;                        
}

...
相关问题