Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Dealing with nextline of a file

by tybalt89 (Monsignor)
on Jul 28, 2021 at 01:17 UTC ( [id://11135413]=note: print w/replies, xml ) Need Help??


in reply to Dealing with nextline of a file

Here's two creative ways - slurp the whole file, then use regex lookahead to get the "next" line, or use tell() and seek() to read ahead then reset the current file position.

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11135401 use warnings; open my $fh, '<', \<<END or die; line one line two line three line four line five END { local $/; local $_ = <$fh>; while( /^(.*)\n(?=(.*))/gm ) { print "$1 -> $2\n"; } } print "\n"; seek $fh, 0, 0; # reset for different example while( <$fh> ) { chomp; my $pos = tell $fh; print"$_ -> ", (<$fh> // "AT LAST LINE\n"); seek $fh, $pos, 0; }

Outputs:

line one -> line two line two -> line three line three -> line four line four -> line five line five -> line one -> line two line two -> line three line three -> line four line four -> line five line five -> AT LAST LINE

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11135413]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-03-29 11:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found