0

As below Perl script shows, it seems $_ is not passed as default parameter to reverse in list context. Why doesn't it just accept $_ as default parameter and do the scalar to list conversion? What's the rule for function's default parameters in both context?

I saw this post, which mentioned @_ should be the default parameter for function which operates in list mode (list reverse, sort), but it doesn't seem to be that case after I prepend @_ = somelist to the below code snippet.

$_ = "dlrow ,olleH";
print reverse;                         # No output, list context
print scalar reverse;                  # Hello, world
Community
  • 1
  • 1
Thomson
  • 20,586
  • 28
  • 90
  • 134
  • Given a choice between `perldoc reverse` & some random post on StackOverflow, choose perldoc every time. – tjd Nov 28 '14 at 03:06
  • @tjd, I read though the page for reserve but it only mentions default parameter in scalar context. I may miss some part. – Thomson Nov 28 '14 at 03:13
  • 1
    That's because there is no defined default input for list context. The accepted answer from the question you referenced was little more than fantacy. – tjd Nov 28 '14 at 03:18

1 Answers1

2

$_ would be a strange default for reverse in list context, since it wouldn't actually do anything:

$_ = "dlrow ,olleH";
print reverse $_;  # outputs: dlrow ,olleH

I don't know what you mean by "scalar to list conversion".

There is no general rule for default parameters for functions, just as there is no general rule for what functions to in list vs. scalar context; you must consult the documentation for each function.

ysth
  • 96,171
  • 6
  • 121
  • 214
  • For "scalar to list conversion", I mean accept $_ as default param, and convert it to list if the function requires list. – Thomson Nov 28 '14 at 05:22
  • @Thomson, `$_` is by definition a scalar. In what way would you "convert it to list"? Split on whitespace? Split on the null pattern? Dereference an arrayref? – cjm Nov 28 '14 at 05:53
  • @cjm, the simple conversion, $_ to ($_) – Thomson Nov 28 '14 at 07:06
  • 2
    @Thomson, as ysth pointed out in his answer, in list context `reverse $_` is a synonym for `$_`. Therefore, it doesn't make any sense for `reverse` to use `$_` as its default parameter in list context. – cjm Nov 28 '14 at 07:36