in reply to Look ahead and join if the line begins with a +

my @list; #Read first, ask questions later is probably not optimal for this #Scope our variable, merge, read, and assign all at once while(chomp(my $line = <NETLIST>)){ #Save a match, substitution returns true iff we susbtituted if ($line =~ s/^\+//){ #Append to previous line (last line in the array) $list[-1] .= $line; } else{ #Save the line push(@list, $line); } } #Map is good, nice way to get all the newlines back #join would work if you the file need not end in a newline print map {"$_\n"} @list;
=>
my @list; while(chomp(my $line = <NETLIST>)){ #Trinary is good ;-) $line =~ s/^\+// ? $list[-1] .= $line : push(@list, $line); } print map {"$_\n"} @list;
=>
my @list; #for is very perlish, so is using $_ chomp && $_ =~ s/^\+// ? $list[-1] .= $_ : push(@list, $_) for <NETLIS +T>; print map {"$_\n"} @list;

--
perl -pe "s/\b;([mnst])/'\1/mg"

Replies are listed 'Best First'.
What if last line has no LF?
by RMGir (Prior) on Apr 11, 2002 at 10:46 UTC
    You wrote:
    while(chomp(my $line = <NETLIST>)){
    What if the last line is missing its \n?

    Since chomp will return 0 if no characters are removed, it's probably safer to go for the less fun

    while(defined(my $line = <NETLIST>)){ chomp;

    --
    Mike

    Edit:Forgot the defined, needed in case of last lines containing only perlish false values, like 0...

      Simple, you don't do that ;-). Seriously, you have a valid point but I don't think it's unreasonable to know your data. It's also not unreasonable to code in a seemingly data independent manner either, but it may just be a throw away tool.

      You could also test to $_ upon exiting the loop, and act accordingly, probably undef'ing $_ withing the loop on each execution.

      --
      perl -pe "s/\b;([mnst])/'\1/mg"

Re: Re: Look ahead and join if the line begins with a +
by petral (Curate) on Apr 11, 2002 at 18:57 UTC
         #Map is good, nice way to get all the newlines back {local $"="\n"; print "@list\n"}

      p
      Cool, but does the interpolation cost much (for a large list)?

      --
      perl -pe "s/\b;([mnst])/'\1/mg"

        Good point.   {local $,="\n"; print @lines,"\n"}

          p