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

Hi monks,
Im a new bie in Perl.
I want to use shift function in the regex as follows,
perl -e '$var=~s/^(shift)$/\u$1/ge;print $var' hi
Expected result: Hi
Please help me on this

Replies are listed 'Best First'.
Re: use shift function in regex
by ikegami (Patriarch) on Nov 24, 2009 at 07:05 UTC
    Two problems.
    • You never put anything in $var, so unless you pass the empty string as an argument, it will never match.

    • \u$1 is not valid Perl code. \u is for use in string literals. So drop the "e" modifier.

    • By the way, the "g" modifier makes no sense either. How can ^ match more than once?

    I think you meant

    perl -le'($var = shift) =~ s/(.*)/\u$1/s; print $var' hi

    But why the crazyness?

    perl -le'print uc(shift)'
Re: use shift function in regex
by CountZero (Bishop) on Nov 24, 2009 at 07:21 UTC
    You do not get a result because you never load $var with a value.

    Try this:

    perl -e "$var = shift; $var=~s/^($var)$/\u$1/;print $var;" hi
    (use single quotes if you are not on Windows)

    Note that the /e modifier only works on the substitution part of the regex, never on the pattern part. Adding /e, does not magically make shift get the argument out of the argument list.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      That should be

      perl -e "$var = shift; $var=~s/^(\Q$var\E)$/\u$1/s; print $var;" hi

      Text treated as a pattern doesn't (necessarily) match itself.

        Thanks ALL for explaining me the right way to perform the task :)
Re: use shift function in regex
by GrandFather (Saint) on Nov 24, 2009 at 06:21 UTC

    (Ignoring the plethora of problems with your sample code) you could:

    s/^@{[shift]}$/\u$1/ge

    True laziness is hard work
    A reply falls below the community's threshold of quality. You may see it by logging in.