简体   繁体   English

如何通过命令行参数读取文本文件并使用perl打印列?

[英]How to read the textfile by command line arguments and print the column by using perl?


How to read the text file using perl command line arguments and print the third column using perl? 如何使用perl命令行参数读取文本文件并使用perl打印第三

I'm struck with taking input from the command line and printing the required column. 我很惊讶从命令行输入并打印所需的列。 Help me to choose the right way to reach the expected output. 帮助我选择正确的方法来达到预期的输出。

Code which I wrote to take command line input:( map.pl ) 我编写以接受命令行输入的代码:( 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";

Output I got for above code: 我得到上面代码的输出:

perl map.pl -p_file cat.txt
p_file = cat.txt

cat.txt:( Input file ) cat.txt :( Input file

ADG:YUF:TGH
UIY:POG:YTH
GHJUR:"HJKL:GHKIO

Expected output: 预期产量:

TGH
YTH
GHKIO

Perl can automatically read files whose names are provided as command line arguments. Perl可以自动读取其名称作为命令行参数提供的文件。 The command below should produce your expected output 以下命令应产生预期的输出

perl -F: -le 'print $F[2]' cat.txt

-F: turns on autosplit mode, sets the field separator to : and loops over lines of input files. -F:打开自动autosplit模式,将字段分隔符设置为:并在输入文件的行上循环。 -l handles line endings during input and output. -l在输入和输出期间处理行尾。 The code after e flag ( 'print $F[2]' prints 3rd field) is executed for each line of file. 对文件的每一行执行e标志之后的代码( 'print $F[2]'打印第三个字段)。 Find out more by reading perldoc perlrun . 阅读perldoc perlrun了解更多perldoc perlrun

You'd need to read the file and split the lines to get the columns, and print the required column. 您需要阅读文件并分割行以获取列,然后打印所需的列。 Here's a demo code snippet, using the perl -s switch to parse command line arguments. 这是一个演示代码段,使用perl -s开关来解析命令行参数。 Run like this ./map.pl -p_file=cat.txt 像这样运行./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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM