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

Mindful Monks,

this code snippet:

$delimiter = "|"; $line = "|45.55.186.846|asdf|24_12:20:19|ab|2004|18467|409|19|us|22348 +|i|cnor|f|55p|2"; $line =~ s/$delimiter/\,/g; print "$line\n";
produces the output:

,|,4,5,.,5,5,.,1,8,6,.,8,4,6,|,a,s,d,f,|,2,4,_,1,2,:,2,0,:,1,9,|,a,b,|,2,0,0,4,|,1,8,4,6,7,|,4,0,9,|,1,9,|,u,s,|,2,2,3,4,8,|,i,|,c,n,o,r,|,f,|,5,5,p,|,2,

whereas I was looking for:

,45.55.186.846,asdf,24_12:20:19,ab,2004,18467,409,19,us,22348,i,cnor,f,55p,2

Something obvious undoubtedly.
Thanks.

Forget that fear of gravity,
Get a little savagery in your life.

Replies are listed 'Best First'.
Re: Using variable in substitute regex producing odd results
by Errto (Vicar) on Sep 06, 2005 at 23:26 UTC
    The pipe character "|" is a regex metacharacter, so your regex becomes "match nothing or nothing" which, with the /g modifier, is effectively equivalent to matching at the boundary between every adjoining character in your string. The generic solution for this is to escape the string within the regexp:
    $line =~ s/\Q$delimeter\E/,/g;
Re: Using variable in substitute regex producing odd results
by GrandFather (Saint) on Sep 06, 2005 at 23:26 UTC

    You need to quote your string with \Q\E because it contains | which in a regex means or. What you want is:

    $line =~ s/\Q$delimiter\E/\,/g;

    Note that your original code acted as a "match anything" so it interspersed a comma between each character in the target string.


    Perl is Huffman encoded by design.
Re: Using variable in substitute regex producing odd results
by sh1tn (Priest) on Sep 06, 2005 at 23:28 UTC
    You may want to look at \Q \E operators:
    ... $line =~ s/\Q$delimiter/\,/g; ...


Re: Using variable in substitute regex producing odd results
by punch_card_don (Curate) on Sep 06, 2005 at 23:32 UTC
    Yep, that did it - thanks all.

    Forget that fear of gravity,
    Get a little savagery in your life.