Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Perl script to read from a text file

by shilpam (Sexton)
on Apr 12, 2004 at 04:32 UTC ( #344323=perlquestion: print w/replies, xml ) Need Help??
shilpam has asked for the wisdom of the Perl Monks concerning the following question:

I have a text file where each new record starts on a new line and for each record the fields are tab delimited. The text file looks something like:
ID1\t NAME1\t AGE1\t LOCATION1 \n<br> ID2\t NAME2\t AGE2\t LOCATION2 \n<br> ID3\t NAME3\t AGE3\t LOCATION3 ... and so on
Further I know that the ID field will take 10 spaces, the NAME field will take 15 spaces, AGE field will take 2 spaces and LOCATION field will take 20 spaces.

I want my Perl script to read this text file and store each record in an array. That means it should store ID1, NAME1, AGE1 and LOCATION1 in array1 and ID2, NAME2, AGE2 and LOCATION2 in array2, and so on...
Can someone help me to write this script?

Replies are listed 'Best First'.
Re: Perl script to read from a text file
by davido (Archbishop) on Apr 12, 2004 at 04:39 UTC
    Since you know the records' individual fields to be delimited by \t, and to be of a fixed width, you can use either split or unpack to grab each field. I chose split just because it's a more common idiom.

    my $infile = "filename.dat"; my @records; { open my $fh , "<", $infile or die "Can't open $infile!\n$!"; my @records = map { chomp; [ split /\t/ ] } <$fh>; } { local $" = "\t"; print "@{$_}\n" foreach @records; }

    Each record is held in an anonymous array, referenced by the top level array, @records.

    Update: Be sure that if you turn this in as homework you've studied the idioms so that you can explain them. There's a good chance your professor hasn't yet covered everything I (intentionally) used in this example.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://344323]
Approved by kvale
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2018-05-20 20:01 GMT
Find Nodes?
    Voting Booth?