in reply to Re: Upper case first letter of each _ delimited word
in thread Upper case first letter of each _ delimited word

sub ucwords { (my $new = $_[0]) =~ s/(?<=$_[1])(\w)/\u$1/sg; return $new; }


japhy -- Perl and Regex Hacker

Replies are listed 'Best First'.
Re: Re: Re: Upper case first letter of each _ delimited word
by chipmunk (Parson) on Dec 05, 2000 at 03:10 UTC
    That's a nice solution, but but I think it is missing a couple features: it doesn't catch the first word in the string; it doesn't lowercase the rest of each word; and it doesn't allow variable-width delimiters. Here's a modified version that addresses those issues.
    sub ucwords { my($new, $delim) = @_; $new =~ s/($delim|^)(.*?)(?=$delim|$)/$1\u\L$2/sg; $new; }
    To match an entire word, from one delimiter to the next, I used a non-greedy match and a positive lookahead.
Re: Re: Re: Upper case first letter of each _ delimited word
by btrott (Parson) on Dec 05, 2000 at 03:01 UTC
    That's slick but it doesn't quite work:
    print ucwords("BATCH_USER_INFO", "_"), "\n"; print ucwords("batch_user_info", "_"), "\n";
    produces
    BATCH_USER_INFO batch_User_Info
    In the first case you don't ever lower-case the string; in the second case you don't look for "word" at the beginning of the string, before the delim.