$/在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";