$/在perl中是输入记录分隔符,影响perl对"行"的理解。默认是换行符"\n".也可以定义为其他的内容:
需要特别注意的是,$/的值是字符串,不是模式匹配。
1> 不修改$/的内容,默认为"\n"
eg: test.pl
open WRI, "<test.pl";
$content = <WRI>; #读取一行
@lines = <WRI>; #将读取的所有行放入@lines数组中。
close WRI;
#foreach my $line (@lines){
# print "$line";
#}
print "$content";
输出:
test]# perl test.pl
open WRI, "<test.pl";
test]#
2> 修改$/的值为某一字符串:
open WRI, "<test.pl";
print "$/";
local $/ = "7799"; #或者是local $/=7799
#$content = <WRI>;
@lines = <WRI>;
close WRI;
$l = 1 ;
foreach my $line (@lines){
print "line $l: $line\n";
$l++;
}
输出:
test]# perl test.pl
line 1: open WRI, "<test.pl";
print "$/";
local $/ = "7799
line 2: ";
#$content = <WRI>;
@lines = <WRI>;
close WRI;
$l = 1 ;
foreach my $line (@lines){
print "line $l: $line\n";
$l++;
}
#print "$content";
test]#
3> $\改成undef
open WRI, "<test.pl";
local $/ = undef;
#$content = <WRI>;
@lines = <WRI>;
close WRI;
$l = 1 ;
foreach my $line (@lines){
print "line $l: $line\n";
$l++;
}
#print "$content";
输出:
test]# perl test.pl
line 1: open WRI, "<test.pl";
local $/ = undef;
#$content = <WRI>;
@lines = <WRI>;
close WRI;
$l = 1 ;
foreach my $line (@lines){
print "line $l: $line\n";
$l++;
}
#print "$content";
eg2:
open WRI, "<test.pl";
local $/ = undef;
$content = <WRI>;
#@lines = <WRI>;
close WRI;
#$l = 1 ;
#foreach my $line (@lines){
# print "line $l: $line\n";
# $l++;
#}
print "$content";
输出:
test]# perl test.pl
open WRI, "<test.pl";
local $/ = undef;
$content = <WRI>;
#@lines = <WRI>;
close WRI;
#$l = 1 ;
#foreach my $line (@lines){
# print "line $l: $line\n";
# $l++;
#}
print "$content";
4>如果$/设为整数、存有整数的标量或可转换成整数的标量这些值的引用时,Perl会尝试读入记录而不是行,最大记录长度就是引用的那个整数。
eg:
open WRI, "<test.pl";
local $/ = \7; #以7个记录为一行分开。
#$content = <WRI>;
@lines = <WRI>;
close WRI;
$l = 1 ;
foreach my $line (@lines){
print "line $l: $line\n";
$l++;
}
输出:
test]# perl test.pl
line 1: open WR
line 2: I, "<te
line 3: st.pl";
line 4:
local
line 5: $/ = \7
line 6: ;
#$con
line 7: tent =
line 8: <WRI>;
line 9: @lines
line 10: = <WRI>
line 11: ;
close
line 12: WRI;
$
line 13: l = 1 ;
line 14:
foreac
line 15: h my $l
line 16: ine (@l
line 17: ines){
line 18: pri
line 19: nt "lin
line 20: e $l: $
line 21: line\n"
line 22: ;
$
line 23: l++;
}
line 24:
#print
line 25: "$cont
line 26: ent";