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

I am sushil i hav a small doubt Why does (`print reverse "dog"') => prints `dog', but (`print ucfirst reverse "dog"') prints `God'?

Replies are listed 'Best First'.
Re: reverse of string
by derby (Abbot) on May 20, 2006 at 12:38 UTC

    It's all about context. reverse by default works on a list in this case is in list context. Since there's only one list item ("dog"), it's printed out. In the second example, ucfirst forces the reverse into scalar context and in scalar context, reverse, combines all the elements of the list and returns the string value of that combination in reverse order.

    -derby

    Update: Doh!! adrianh is correct.

      reverse by default works on a list

      <niggle> Nope. reverse doesn't have a default behaviour. In list context it reverses a list. In scalar context it reverses a string. The print puts the reverse into a list context, hence the behaviour that confused the OP. </niggle>

Re: reverse of string
by borisz (Canon) on May 20, 2006 at 12:41 UTC
    print reverse 'dog'; reverse is in list context and reverts a list of someting. your list has only one entry 'dog'.
    for print ucfirst reverse "dog"; reverse is in scalar context and reverts a string instead of a list.
    Boris
Re: reverse of string
by Cody Pendant (Prior) on May 20, 2006 at 12:41 UTC
    In order to reverse a string, you need to use
    print scalar reverse "dog"
    because reverse expects an array unless told otherwise. So ... because ucfirst is forcing scalar context onto "reverse"?


    ($_='kkvvttuu bbooppuuiiffss qqffssmm iibbddllffss')
    =~y~b-v~a-z~s; print
      Thanx for your reply, Most of them said it since it by default considers as a list so anyway its good that you have also sent me the code to print it thank you Sushil
Re: reverse of string
by zerogeek (Monk) on May 20, 2006 at 15:50 UTC
    This being the first node that I have read that references "God", I thought it odd that the node# ended in 666...

    Must be an idle thread running through my brain this morning ;)