in reply to $1 $2 Weirdness?

Because in ~s/(\w)(\s)(\w)/$1/eig (\w) matches one character, (\s) matches one character and (\w) matches one character. So in "Sam Adams" m A, gets matched and replaced with m.

What you more likely want is:

$name=~s/(\w*?)(\s).*/$1/eig;

Perl is Huffman encoded by design.

Replies are listed 'Best First'.
Re^2: $1 $2 Weirdness?
by bart (Canon) on Jun 27, 2005 at 08:40 UTC
    What you more likely want is:
    $name=~s/(\w*?)(\s).*/$1/eig;
    I don't think so. yet more cargo cult regexing, huh? *sigh*

    Let's strike all the unnecessary cruft.

    • He wants +, not *. What if his string started with a space?
    • The ? is unnecessary
    • I see no reason to replace \w+ with .*
    • The /e modifier is totally useless, though by accident, harmless
    • The /i modifier is useless
    • If you use .*, then the /g modifier is useless

    Granted, the modifiers you inherited from the OP, but for the rest I see very little excuse.

    IMO this is what the OP is after:

    $name=~s/(\w+)(\s)(\w+)/$1/g;
    or even
    $name=~s/(\w+)\s\w+/$1/g;
    though it would likely also do what he wants without the /g.

      Yes to all of that. I was cruising through the afternoon and spotted his immediate problem without actually engaging my brain and looking at the big picture. sigh. By the time I noticed it was too late to retract and others had pointed out the problems anyway.


      Perl is Huffman encoded by design.
Re^2: $1 $2 Weirdness?
by apt_get (Acolyte) on Jun 27, 2005 at 00:18 UTC
    Thanks all, for your replies. For some brain dead reason, I was assuming the "\w" to match a "more than one character" word, instead of just a single character. Now I know.