I'm just starting out in Perl and I'm trying to loop over lines of text to do this task....
Write a script which assembles separate lines in to longer lines. A new line in the output is one that starts with at least two digits. All the lines which follow it, until the next occurrence of two digits at the start of a line, are a continuation of the earlier line. Eg
21 this
is all part
of
the same line
223 but this is different
$var = "";
while (<123 a line of text \nthis line should be the same as the first \n145 but this one should be different>) {
if (/^\d\d/) {
print "$var\n";
$var = ""
}
$var .= $_;
}
print "$var\n"; # any leftover?
I am aware that the above which is my version is meaningless but I'm sure if somebody could word it nicely I'd understand how to use the real solution that was given
open(FH,"<somfile.txt");
while (<FH>) { # yadda yadda yadda
Do you have to be working with file contents though?
perldoc.com wrote:
In scalar context, evaluating a filehandle in angle brackets yields the next line from that file (the newline, if any, included), or undef at end-of-file or on error.
Isn't it possible to create some variable with a long string containing \n and use that?
I'm just starting out in Perl and I'm trying to loop over lines of text to do this task....
Write a script which assembles separate lines in to longer lines. A new line in the output is one that starts with at least two digits. All the lines which follow it, until the next occurrence of two digits at the start of a line, are a continuation of the earlier line. Eg
21 this
is all part
of
the same line
223 but this is different
Thus you start with coming up with an algorithm.
One would be: as long as there is input, read in the line.
If the line starts with 2 decimals, append it to what we have.
Else add the previous stuff to the results, and build a new string
my @lines; # here we store the results
my $current = ''; # to start we have nothing
while (<>) # while there are lines we read from <STDIN> into $_
{
if (/^\d\d) # the line starts with 2 decimals
{
$current .= $_; # we append
}
else
{
push(@lines, $current); # what we currently have is a complete line
$current = $_; # we start to build a new line
}
}
# done ;)
Got it figured in the end. I'm having a little trouble with a pattern match to extract hyperlink information from html documents now but i've posted that in a separate post so I shouldn't really mention it here.