Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl while(<DATA>){ s/\+//g; print $_; } __DATA__ + 5 + 45 +
Here '+' character is removed from the entire line. I just want to remove the middle one. Any help is appreciated

Replies are listed 'Best First'.
Re: character from middle
by Utilitarian (Vicar) on Sep 01, 2009 at 09:10 UTC
    So you don't want to remove a literal + followed by an end of string or preceded by a start of string.

    You could lookahead and lookbehind for not start/end of string.

    Take a look in perlre for (?!pattern) and (?<!pattern)

Re: character from middle
by jwkrahn (Abbot) on Sep 01, 2009 at 09:26 UTC
    #!/usr/bin/perl use warnings; use strict; while ( <DATA> ) { my @x; push @x, $-[ 0 ] while /\+/g; substr $_, $x[ @x / 2 ], 1, ''; print; } __DATA__ + 5 + 45 +
Re: character from middle
by JavaFan (Canon) on Sep 01, 2009 at 09:53 UTC
    You need to do it in three steps. First you count the number of '+'s. Second, you decide which one is the middle. Third, you remove that one from string.
Re: character from middle
by ig (Vicar) on Sep 01, 2009 at 13:48 UTC

    You should think about how "the middle one" is different from the others and you should think about other data records and what you want done with them. What results would you want with the following lines?

    + 1 + 2 + 3 + + 1 + 2 + 3 + 4 + +1+2+3+ +1+2+3+4+ ++1+2++ 1 + 2 1 + 2 + 3 1 + 2 + 3 + 4
Re: character from middle
by arun_kom (Monk) on Sep 01, 2009 at 09:26 UTC
    Modifying your code like so seems to work.

    while(<DATA>){ s/(.+)\+(.+)/$1$2/g; print $_; }
    A better way could be the one mentioned in the above post.

      Consider the data
      __DATA__ + 5 + 23 + 223 + 34 + 45 +
      Your solution will remove the last instance of "+" ie.
      + 5 + 23 + 223 + 34 45 +
      Depends on the expected data and required result, the presence of the /g operator made me suspect that the above data was likely