在perl中按行或空格递增
我想读取两种格式的文件:在perl中按行或空格递增,perl,Perl,我想读取两种格式的文件: x 512 512 255 及 我想将它们存储为单个变量。由于这两种格式,我不能简单地将每行的输入放入变量中。 是否有任何方法可以通过空格和换行来增加文件的长度 这是我的代码,它只采用第二种格式 #!/usr/bin/perl -w use strict; my $fileType; my $fileWidth; my $fileHeight; my @lineTwo; my $inputFile = $ARGV[0]; open(my $file, "<"
x 512 512 255
及
我想将它们存储为单个变量。由于这两种格式,我不能简单地将每行的输入放入变量中。是否有任何方法可以通过空格和换行来增加文件的长度 这是我的代码,它只采用第二种格式
#!/usr/bin/perl -w
use strict;
my $fileType;
my $fileWidth;
my $fileHeight;
my @lineTwo;
my $inputFile = $ARGV[0];
open(my $file, "<", $inputFile) or die;
while (my $line = <$file>){
if($. == 1){
$fileType = $line;
chomp $fileType;
}elsif($. == 2){
@lineTwo = split(/\s/,$line);
$fileWidth = $lineTwo[0];
$fileHeight = $lineTwo[1];
}
last if $. == 2;
}
print "This file is a $fileType file\n";
print "Width of image = $fileWidth\n";
print "Height of image = $fileHeight\n";
#/usr/bin/perl-w
严格使用;
我的$fileType;
我的$fileWidth;
我的身高;
我的@lineTwo;
my$inputFile=$ARGV[0];
打开(my$file,“只需将文件拖出并在空白处拆分(包括空格或换行符):
!/usr/bin/perl-w
严格使用;
使用警告;
使用自动模具;
my$inputFile=shift;
我的($fileType,$fileWidth,$fileHeight)=拆分/\s+/,是否{
本地$/;
打开我的$fh,“只需轻声读文件并在空白处拆分(包括空格或换行):
!/usr/bin/perl-w
严格使用;
使用警告;
使用自动模具;
my$inputFile=shift;
我的($fileType,$fileWidth,$fileHeight)=拆分/\s+/,是否{
本地$/;
打开我的$fh,“继续从文件中获取字段,直到有三个或更多字段
无需显式打开在命令行上作为参数传递的文件,因为
将隐式打开并按顺序读取所有文件
use strict;
use warnings;
my @data;
while (<>) {
push @data, split;
last if @data >= 3;
}
my ($type, $width, $height) = @data;
print "This is a $type file\n";
print "Width of image = $width\n";
print "Height of image = $height\n";
只要继续从文件中提取字段,直到有三个或更多字段
无需显式打开在命令行上作为参数传递的文件,因为
将隐式打开并按顺序读取所有文件
use strict;
use warnings;
my @data;
while (<>) {
push @data, split;
last if @data >= 3;
}
my ($type, $width, $height) = @data;
print "This is a $type file\n";
print "Width of image = $width\n";
print "Height of image = $height\n";
您的意思可能是拆分“”
:)您的意思可能是拆分“”
:)如果您要编写自己的ppm解析器,请遵循规范()它允许任何类型的空格用于任何分隔符,而不仅仅是您迄今为止观察到的2种组合。如果您要编写自己的ppm解析器,请遵循spec(),它允许任何类型的空格用于任何分隔符,而不仅仅是您迄今观察到的2种组合。
#!/usr/bin/perl -w
use strict;
use warnings;
my ($fileType, $fileWidth, $fileHeight) = split ' ', do {
local $/;
<>;
};
use strict;
use warnings;
my @data;
while (<>) {
push @data, split;
last if @data >= 3;
}
my ($type, $width, $height) = @data;
print "This is a $type file\n";
print "Width of image = $width\n";
print "Height of image = $height\n";
This is a x file
Width of image = 512
Height of image = 512