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


Greetings to all

I used the following code to successfully split a string on underscore and capitalize the first letter of each word so obtained.

$c = 'a_c_code'; print join " ", map { ucfirst } split /_/, $c;

Was wondering if there is a one line regex to do this. I tried but could not come up with one, if there is no underscore character in the string.
Thanks all

--
arc_of_descent

Replies are listed 'Best First'.
Re: split and capitalize regex
by PodMaster (Abbot) on Jan 13, 2004 at 11:52 UTC
    I tried but could not come up with one, if there is no underscore character in the string.
    You should always show what you tried. Here's my shot from what I think you're saying
    $_ = 'a_c_code'; s{ ([^_]+) | (_) }' $2 ? " " : ucfirst $1 'gxe; print $_,$/; __END__ A C Code
    You could also y/_/ / first, then s/(\w+)/\u$1/g;

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

Re: split and capitalize regex
by Roger (Parson) on Jan 13, 2004 at 12:14 UTC
    Two methods I can think of ...

    # method 1 print qq{@{[ map { ucfirst} $c =~ /([^_]+)/g ]}}; # method 2 $c =~ s/([^_]+)|_/ucfirst $1 or ' '/ge; print "$c\n"; # method 2 - updated version # just realized there might be a problem if the pattern # $c = '0_a_c_code', where 0 also evaluates to false $c =~ s/([^_]+)|_/defined($1) ? ucfirst $1 : ' '/ge; print "$c\n";
Re: split and capitalize regex
by BrowserUk (Patriarch) on Jan 13, 2004 at 15:18 UTC

    This seems to work.

    $s = 'the_quick_brown_fox_jumps_over_the_lazy_dog'; $s =~ s[(.)([^_]*?)(?:_|$)][\U$1\E$2 ]g; print $s; The Quick Brown Fox Jumps Over The Lazy Dog $s = 'fred'; $s =~ s[(.)([^_]*?)(?:_|$)][\U$1\E$2 ]g; print $s; Fred

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    Timing (and a little luck) are everything!

Re: split and capitalize regex
by ysth (Canon) on Jan 13, 2004 at 15:51 UTC
    $c = "a_c_code"; $c =~ s/(?<![^_])(.)/ucfirst($1)/ge; print $c;
    This ucfirsts any character that doesn't follow a non-_. (The double-negative condition is a more terse way of saying "follows a _ or at the beginning of a string": s/(?:\A|(?<=_))(.)/ucfirst($1)/ge.)

    Why ucfirst instead of uc when only dealing with one character? Because there are ligature characters (the only latin1 instance being "\xdf") where the two produce different results.