in reply to Re: Questions on sort
in thread Questions on sort

what is the purpose of putting the "[0]" in the second code? I got the same output with the "[0]" removed.

>perl -E "say('abc123def' =~ /(\d+)/);" 123

Replies are listed 'Best First'.
Re^3: Questions on sort
by jwkrahn (Abbot) on Aug 16, 2011 at 06:56 UTC

    In the code ($a =~ /(\d+)/)[0] <=> ($b =~ /(\d+)/)[0] the regular expression is used in a list slice with a single index which returns a scalar value which can be compared with the <=> operator.    Without the list slice the regular expression would return TRUE or FALSE in scalar context.

    In the code my($aa) = $a =~ /(\d+)/; the parentheses around $aa impose list context on the regular expression which in list context returns all the contents of capturing parentheses in the regular expression.

      ++   ...   Read the above post five times in a row.

Re^3: Questions on sort
by ikegami (Patriarch) on Aug 16, 2011 at 06:49 UTC

    The original code didn't use say, though. It used something that placed the expression scalar context, and there it makes a difference.

    >perl -E"say(scalar( 'abc234def' =~ /(\d+)/ ));" 1 >perl -E"say(scalar( ('abc234def' =~ /(\d+)/)[0] ));" 234
Re^3: Questions on sort
by Anonymous Monk on Aug 16, 2011 at 06:27 UTC
    Its the same purpose they would serve in an array
    print( ( 4,6,8 )[0] )