我正在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;
}
...
编辑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;
}
...
控制台输出:
答案 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/;
}
...