使用local时,我对范围进行了很多搜索。
我从这里了解到:http ://www.perlmonks.org/?node_id=94007它会在执行“本地”行和到达下一个块的末尾之间临时更改变量的值。但是,它似乎也“回滚”了 perl 阅读光标?它似乎保留了以前的$_。
这些是我的 perl 脚本的要求:
在标准输入上,读取一个文本文件。如果当前行匹配==,则将行上的字符串打印为具有相应格式的html片段(==,===,====中的每个格式不同)如果它包含!,打印!之前的部分 作为属性名称和 ! 之后的部分 直到下一个!作为值(可能跨越多行)。
这是一个示例文件:
$ cat dummy_spec.txt
== title1 (level 1) ==
=== title2 (level 2) ===
title2p2 !
2p2_1
!
title2p2 ! Line 1
!
title2p1 !
echo "$tam ta"
!
title2p3 !
2p3
!
title2p2 ! Li
ne split
!
==== title3 (level 3) ====
title3p1 !
one
two
three
!
这是我的代码:
#!/usr/bin/env perl
my $propName='';
my $propVal='';
while (<>){
#print "new loop number $., contents $_ \n";
$propName='';
$propVal='';
my $str=$_;
chomp $str;
if ($str=~/==\s+.+\s+==/)#If line is a Category, print category
{
$str=~s/=//g;
print "\t\t\t<tr class=\"category\"><td colspan=\"2\">$str</td></tr>\n";
} elsif($str=~/===\s+.+\s+===/)#If line is a list, print list title
{
$str=~s/=//g;
print "\t\t\t<tr class=\"list\"><td colspan=\"2\">$str</td></tr>\n";
} elsif($str=~/====\s+.+\s+====/)#If line is an item, print item title
{
$str=~s/=//g;
print "\t\t\t<tr class=\"item\"><td>$str</td></tr>\n";
} elsif($str=~/!/)#If line is a property, print name and value
{
($propName,$propVal)=split '!', $_;
chop $propVal;
print "This is a property ($.) with name : $propName and first line : $propVal \n";
local $/ = "!\n";
if(<>){#custom $/ should still be in scope here.
chomp;
$propVal="$propVal -~- $_";
print "This is a property ($.) with name : $propName and value : $propVal \n";
}
}
}
输出不是应该的:
$ cat dummy_spec.txt |./multi
<tr class="category"><td colspan="2"> title1 (level 1) </td></tr>
<tr class="category"><td colspan="2"> title2 (level 2) </td></tr>
This is a property (3) with name : title2p2 and first line :
This is a property (4) with name : title2p2 and value : -~- title2p2
This is a property (5) with name : title2p2 and first line : Line 1
This is a property (6) with name : title2p2 and value : Line 1 -~- title2p2 ! Line 1
This is a property (7) with name : title2p1 and first line :
This is a property (8) with name : title2p1 and value : -~- title2p1 !
This is a property (9) with name : title2p3 and first line :
This is a property (10) with name : title2p3 and value : -~- title2p3
This is a property (11) with name : title2p2 and first line : Li
This is a property (12) with name : title2p2 and value : Li -~- title2p2 ! Li
<tr class="category"><td colspan="2"> title3 (level 3) </td></tr>
This is a property (14) with name : title3p1 and first line :
This is a property (15) with name : title3p1 and value : -~- title3p1
似乎它也“回滚” perl 阅读光标?它打印前一个 $_。
我也很抱歉,因为我的 perl 非常基础。