![](/img/trans.png)
[英]How to pass command line arguments along with perl modules using perl?
[英]How to read the textfile by command line arguments and print the column by using perl?
如何使用perl命令行参数读取文本文件并使用perl打印第三 列 ?
我很惊讶从命令行输入并打印所需的列。 帮助我选择正确的方法来达到预期的输出。
我编写以接受命令行输入的代码:( map.pl
)
use strict;
use warnings 'all';
use Getopt::Long 'GetOptions';
my @files=GetOptions(
'p_file=s' => \my $p_file,
);
print $p_file ? "p_file = $p_file\n" : "p_file\n";
我得到上面代码的输出:
perl map.pl -p_file cat.txt
p_file = cat.txt
cat.txt :( Input file
)
ADG:YUF:TGH
UIY:POG:YTH
GHJUR:"HJKL:GHKIO
预期产量:
TGH
YTH
GHKIO
Perl可以自动读取其名称作为命令行参数提供的文件。 以下命令应产生预期的输出
perl -F: -le 'print $F[2]' cat.txt
-F:
打开自动autosplit
模式,将字段分隔符设置为:
并在输入文件的行上循环。 -l
在输入和输出期间处理行尾。 对文件的每一行执行e
标志之后的代码( 'print $F[2]'
打印第三个字段)。 阅读perldoc perlrun
了解更多perldoc perlrun
。
您需要阅读文件并分割行以获取列,然后打印所需的列。 这是一个演示代码段,使用perl -s开关来解析命令行参数。 像这样运行./map.pl -p_file = cat.txt
#!/usr/bin/perl -s
use strict;
use warnings;
use vars qw[$p_file];
die("You need to pass a filename as argument") unless(defined($p_file));
die("Filename ($p_file) does not exists") unless(-f $p_file);
print "Proceeding to read file : $p_file\n\n";
open(my $fh,'<',$p_file) or die($!);
while(chomp(my $line = <$fh>)) {
next unless(defined($line) && $line);
my @cols = split(/:/,$line);
print $cols[-1],"\n";
}
close($fh);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.