Question:
how can I make a program that takes only the last line of a file using perl?
anonymous
2009-05-12 00:33:48 UTC
for example,if I have written in a .txt file "hi!
how are u?"
I want a line of code(or two)that can save the "how are u?" into a sring or an array.
Three answers:
S T
2009-05-12 03:58:08 UTC
Very inefficient example, slow on big files, but simple:



open(F, '<', '1.txt') or die "Cannot open file, $!";

my $lastline;

while () {

$lastline = $_;

}

close F;

print $lastline;



If you want to get the last line from very big file (10 gigabytes, for example), you should use another technique: reading some chars from the end of file, check "\n" inside and move to the beginning if "\n" is not found.
anonymous
2009-05-12 20:08:54 UTC
ST is right with his answer if you don't want to use a module. His method is going to be slow on a large file.



You might have a look at the File::Tail module http://search.cpan.org/~mgrabnar/File-Tail-0.99.3/Tail.pm



A good rule of thumb when you're trying to do something in Perl is to check CPAN to see if someone's solved your problem already because while it's a nice exercise to re-invent the wheel, it's usually a huge waste of time.



Your other option would be to do a block read from the tail of the file and see if you have a carriage return in the block you get. If you do, you should be able to parse it out from there. That should avoid the time problem if you're trying to do that on a large file.



Here's some sample code from an MP3 editor I wrote a while back that may help you out:



sub readfile{

my $size = (stat($mp3))[7];

$offset = $size-128;

open FH, "<$mp3" or die "Could not open file $mp3\n";

binmode FH;

seek (FH, -128, 2);

read (FH, $tag, 128);

die "No tag to edit!" if $tag !~ /^TAG/;

($info{head}, $info{t}, $info{a}, $info{l}, $info{y}, $info{c}, $info{g}) = unpack("a3a30a30a30a4a30C1",$tag);

close FH;

}



You'll need to read up on stat but the stat($mp3))[7] gets the file size from the MP3 file since an ID31 tag resided at the last 128 bytes of the file I used that technique to get the information without having to read the whole file. Ignore the unpack section as it doesn't apply to what you're trying to do.



Hope that helps!
asbharadwaj
2009-05-12 00:52:34 UTC
try this http://www.microsoft.com/technet/scriptcenter/resources/qanda/mar06/hey0303.mspx


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