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

Hi monks,

Background
I have a set of values an array. Array can be @names = qw(user_name house_name street_address phone_number date_of_birth); I need to remove the "_" from all the values and need to have upper case for all words in each values.

The output I need is

User Name
House Name
Street Address
Phone Number
Date Of Birth

The Question
I tried to write something like

foreach $name ( @names ){ $name = ucfirst($name); # made first letter $name =~ s/\_(\w)/\ uc($1)/g; # Here is the point. print "$name \n"; }
At the line $name =~ s/\_(\w)/\ uc($1)/g; Can I replace the "_" and next character with " " and return value of the function 'uc()', which takes $1 as parameter.

Update: Removed comas from the array as its a bug pointed out by pKai at Re: Interpolation inside regex

Replies are listed 'Best First'.
Re: Interpolation inside regex
by Corion (Patriarch) on Sep 07, 2007 at 08:43 UTC

    Yes. See the /e modifier in perlre:

    foreach $name ( @names ){ $name = ucfirst($name); # made first letter $name =~ s/\_(\w)/\ uc($1)/ge; # Here is the point. print "$name \n"; }

    You can also change that to:

    foreach $name ( @names ){ $name = ucfirst($name); # made first letter $name =~ s/_(\w)/ \U$1/g; print "$name \n"; }

    to avoid the /e. Also, see perlre again for \U and \L.

      Thanks, It works! Thanks!
Re: Interpolation inside regex
by johngg (Canon) on Sep 07, 2007 at 10:08 UTC
    Another way would be to avoid the substitution altogether and use split, ucfirst and join with maps.

    print map { qq{@{ [ join q{ }, map { ucfirst } @$_ ] }\n} } map { [ split m{_} ] } @names;

    I hope this is of use.

    Cheers,

    JohnGG

Re: Interpolation inside regex
by pKai (Priest) on Sep 07, 2007 at 11:38 UTC

    Nitpick: None of the proposed solutions will give you the required output for the @names you showed in the OP!

    D:\temp>perl -we "my @names = qw(user_name, house_name, street_address +, phone_number, date_of_birth);" Possible attempt to separate words with commas at -e line 1.
      remove those comas as we don't need separated when we quote with qw.
      @names = qw(user_name house_name street_address phone_number date_of_b +irth);

      Thanks for pointing out the bug. We all were concentrating on regex and not on the typo. Any way THANKS