Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting first and last line of a file into a $ 1

Status
Not open for further replies.

nook6

Programmer
Dec 18, 2002
24
0
0
GB
Hi

Is there a way that i can read a whole text file but only get the first and last line into $firstline and $lastline

Any help would be greatly appreciated

Nook6
 
As goBoating said in thread219-433768 with minor alterations:
Code:
#!/usr/bin/perl
open IPF, "file_name";
@lines = <IPF>;
$firstline = shift(@lines);
$lastline = pop(@lines);
That what you're looking for? ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Hi

Thankyou very much for your help (just if i knew how easy it would be LMAO)

Nook6
 
If the file is too big to fit in memory at one time, you can try this solution.

==================
$firstline = &quot;&quot;;
$lastline = &quot;&quot;;

open IPF, &quot;filename&quot; or die &quot;Error opening input file: $!&quot;;
$firstline = <IPF>;
while(<IPF>) {$lastline = $_;}
==================

This grabs the first line into $firstline. The location of the next read from the file will be line 2. The while() loop reads the file line by line and assigns the current line to $lastline. When there are no more lines, $lastline contains whatever the last line in the file was.

I explicitly created $lastline ouside the while() loop so there wouldn't be scope issues. Doing that for $firstline wasn't really necessary, but it appealed to my sense of symmetry :).

This is probably slower than reading the whole file into memory, but it should work for arbitrarily large files. If you have confidence that your file size is small enough to fit in RAM, use icrf's solution for speed.

Share and enjoy.
obscurifer
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top