three18ti has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
I would like to parse a file that has single lines split into multiple lines by terminating the line with a "\".
I basically want to read a file line by line and grab all continued lines at once.
I was thinking about something along the lines of:
#/usr/bin/perl use strict; use warnings; use IO::File; use 5.010; my $filename = shift @ARGV; my $fh = IO::File->new($filename, 'r'); my $fh_iterator = sub { my $fh = shift; my $line = $fh->getline; } while (my $line = $fh_iterator->($fh)) { # do stuff to $line }
Where I get stuck is the logic to grab the next line if the line is terminated with a /\\\n/... My first thought was some kind of recursion:
$line .= $fh_iterator->($fh) if $line =~ /\\\n/
(Maybe I should be using a named sub instead of a closure; eventually I would like to include this as part of an object I'm trying to work out the parsing logic first)
I could just be over thinking the problem...
Thanks for your thoughts
Edit: Some further thinking I tried using a named sub instead of a closure
sub fh_iterator { my $fh = shift; my $line = $fh->getline; $line .= fh_iterator($fh) if $line =~ /\\\n/; return $line; }
But each time fh_iterator is called, it's going to clobber $line... So this doesn't do what I'd expect. I'd like to preserve the \ but should probably chomp the $fh->getline somehow.