您好可以有人請解釋一下我爲什麼有不同的輸出從以下兩個腳本的最後一行丟失:Perl的 - 打開文件 - 如果換行沒有最後一行後提出的
01.pl
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
open FDGROUP, "< file" or die "Can't open file: $!\n";
my @file = <FDGROUP>;
close FDGROUP;
@file = grep {/\S/} @file;
@file = grep {s/\r//} @file;
@file = grep {s/\n//} @file;
print Dumper @file;
02.pl
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
open FDGROUP, "< file" or die "Can't open file: $!\n";
my @file = <FDGROUP>;
close FDGROUP;
@file = grep {/\S/} @file;
my $j = 0;
foreach (@file){
$_ =~ s/\r//;
$_ =~ s/\n//;
$file[$j++] = $_;
}
print Dumper @file;
輸出:
[email protected] ~/scripts/stackoverflow
$ perl 01.pl
$VAR1 = '1';
$VAR2 = '2';
$VAR3 = '3';
$VAR4 = '4';
$VAR5 = '5';
$VAR6 = '6';
[email protected] ~/scripts/stackoverflow
$ perl 02.pl
$VAR1 = '1';
$VAR2 = '2';
$VAR3 = '3';
$VAR4 = '4';
$VAR5 = '5';
$VAR6 = '6';
$VAR7 = '7';
[email protected] ~/scripts/stackoverflow
$ od -ab file
0000000 1 cr nl 2 cr nl 3 cr nl 4 cr nl 5 cr nl 6
061 015 012 062 015 012 063 015 012 064 015 012 065 015 012 066
0000020 cr nl 7
015 012 067
0000023
[email protected] ~/scripts/stackoverflow
$ perl -e 'print $/' | od -ab
0000000 nl
012
0000001
當我在我打開腳本文件的最後一行之後再添新行給出了相同的結果(7個變量)。我知道chomp
用於這樣的操作,但是當我用下面的腳本:
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
open FDGROUP, "< file" or die "Can't open file: $!\n";
my @file = <FDGROUP>;
close FDGROUP;
@file = grep {/\S/} @file;
chomp @file;
print Dumper @file;
我獲得以下的輸出:
[email protected] ~/scripts/stackoverflow
$ perl 03.pl
';AR1 = '1
';AR2 = '2
';AR3 = '3
';AR4 = '4
';AR5 = '5
';AR6 = '6
';AR7 = '7
這大概是CR空白或與它的東西引起的。
所有這些都在cygwin下完成。
謝謝
'$ file [$ j ++] = $ _;'是不必要的:http://perldoc.perl.org/perlsyn。html#Foreach-Loops – toolic
謝謝,值得了解它。 –