我想阅读一个可以有两种格式的文件:
x 512 512 255
和
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";
答案 0 :(得分:4)
只需继续从文件中提取字段,直到您有三个或更多。
没有必要在命令行上显式打开作为参数传递的文件,因为<>
将隐式打开并按顺序读取它们。
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
答案 1 :(得分:2)
只是啜饮文件并拆分空格(包括空格或换行符):
#!/usr/bin/perl -w
use strict;
use warnings;
use autodie;
my $inputFile = shift;
my ($fileType, $fileWidth, $fileHeight) = split /\s+/, do {
local $/;
open my $fh, '<', $inputFile;
<$fh>;
};
print "This file is a $fileType file\n";
print "Width of image = $fileWidth\n";
print "Height of image = $fileHeight\n";
如果您对perl的更高级工具感到满意,那么所有这些实际上都可以压缩到以下内容:
#!/usr/bin/perl -w
use strict;
use warnings;
my ($fileType, $fileWidth, $fileHeight) = split ' ', do {
local $/;
<>;
};