user7578786
user7578786

Reputation:

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?

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)

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)

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

Expected output:

TGH
YTH
GHKIO

Upvotes: 1

Views: 2025

Answers (2)

pii_ke
pii_ke

Reputation: 2881

Perl can automatically read files whose names are provided as command line arguments. 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. -l handles line endings during input and output. The code after e flag ('print $F[2]' prints 3rd field) is executed for each line of file. Find out more by reading perldoc perlrun.

Upvotes: 3

Pradeep
Pradeep

Reputation: 3153

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. Run like this ./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);

Upvotes: 1

Related Questions