in reply to Substitution in range operator

If the file size is not too large you could read in the whole text and replace each instance of a new line followed by a pipe, with a space. Then afterwards go through it again line by line and make your other substitutions.

local $/; open my $fh, '<', 'file.txt' or die $!; my $txt = <$fh>; $txt =~ s/\n\|/ /g; for ( split '\n', $txt ) { # process each line }


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Substitution in range operator
by benaw (Novice) on Dec 30, 2015 at 04:48 UTC

    Thanks for your response,

    I created an output file using my original script because that is what puts the pipes in

    ## Substitute 2 or more horizontal white space with pipe s/[\h+]{2,}/|/g;

    then i passed that file through your script it finds the pipe and replaces it with a space but it is still on a separate line.

    #!/usr/bin/perl local $/; open my $fh, '<', 'whitespacegone.txt' or die $!; my $txt = <$fh>; $txt =~ s/(\n\|)/ /mg; for ( split '\n', $txt ) { # process each line } print $txt;

      Hm, odd. Please try running this program:

      #!/usr/bin/perl use strict; use warnings; local $/; my $txt = <DATA>; $txt =~ s/\n\|/ /g; print $txt; __DATA__ foo | bar baz |qux fred |wilma barney
      Output should be :
      foo | bar baz qux fred wilma barney
      (Note that you don't need to enclose your desired match in parentheses unless you need to "capture" it.)


      The way forward always starts with a minimal test.

        Output:

        foo | bar baz qux fred wilma barney

        Perl -v perl 5, version 14 subversion 2 (v5.14.2) built for cygwin-thread-multi-64int