Question:
In perl how to parse a text file?
broad
2008-05-21 00:12:51 UTC
I have a text file which contains some data.It has the data in column wise form..Say the columns are age,name,and number.And below are the values.How can I parse the file in perl so that it will output only the the desired values.e.g it will only output the value for the age field?Can somebody give a small example?Thanks in advance..
Four answers:
Margaritagil
2008-05-21 01:15:06 UTC
Assuming a tab delimited file:





my $lineNumber = 0;



my $inputFile = "c:/path/to/file.txt";



open (FILEHANDLE, "< " . $inputFile) or die "oops: $!";

while() {

   my $lineOfInput = $_;



   $lineNumber++;



#this is if you want to allow perl style comments

   if ($lineOfInput =~ m|^\s*\#|) {

      next;

   }



   my @fields = split ("\t", $lineOfInput);



   #this is if you want to do a little validation.

   if ((scalar @fields) < 3) { #if the number of columns found is less than 3

      #then it's a bad record so handle it.

      print STDERR ("Bad record at line: $lineNumber!\n"); #Print to standard error

   }

   else {

      my $nameField = $fields[0];

      my $ageField = $fields[1];

      my $numberField = $fields[2];



      print STDOUT ("Hello, $nameField, you $ageField year old with number $numberField\n"); #print to Standard output console

   }



}

close(FILEHANDLE);
dw
2008-05-21 01:44:13 UTC
Here's a neat trick to boost your command line perl-fu:



$> perl -F' ' -lane 'print $F[1]' file.txt

Age

22

21



$> perl -F' ' -lane 'print $F[0]' file.txt

Name

xyz

abc



$> perl -F' ' -lane 'print $F[2]' file.txt

Number

123456

234567





$> cat file.txt

Name Age Number

xyz 22 123456

abc 21 234567
yoga_sawant
2008-05-21 05:11:51 UTC
This perl script will parse the text file and print only age:



#!/usr/bin/perl

# parse_text.pl

use strict;

use warnings;

while (my $line =<>) {

next if ($line =~ m/^$/); # Skip empty lines

next if ($line =~ m/^\s*#/); # Skip comments

if ($line =~ m/^(.*?)\s+(\d+)\s+(\d+)/) {

print $2 . "\n";

}

}



Run this perl script as: parse_text.pl datafile



If you want to display name and age, then change this: print $2 . "\n";

to this: print $1 . "\t" . $2. "\n";



$1, $2, and $3 would get you name, age, and number respectively
2016-09-29 06:08:03 UTC
a million. i don't be attentive to what iternate skill. 2. at the same time as (my $sLine = <>) { } 3. my @asItem = chop up(qr{,}, $sLine); my %hash = map { $_ => a million } @asItem; i anticipate you be attentive to that this won't paintings if any of the CSV values incorporates comma or carriage-return.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...