Why do function arguments invoke a list context?

I have a function that depends on the context of the call, and I wanted to use this function as an argument for another function. Surprisingly, I found that this function secondis called in the context of the list now. I tried scalar context with help +(), but it does not work as I expected. Thus, the only way is to implicitly call it scalar.

use 5.010;

say first( 1, second( 'y' ) );
say first( 1, +( second( 'y' ) ) );
say first( 1, scalar second( 'y' ) );

sub first {
  my $x = shift;
  my $y = shift;

  return "$x + $y";
}

sub second {
  my $y = shift;

  if ( wantarray ) {
    qw/ array array /;
  } else {
    'scalar';
  }
}
__END__
1 + array
1 + array
1 + scalar

Function arguments are treated as a list, but does this mean that each argument in this list also implies a list context? If so, why?

And, using scalarworks, but what other ways should I call this function in a scalar context (without an intermediate variable)?

+4
2

?

. ?

, , ? , ?

. . , .

%h = (%h, ...);  # Add to a hash
f( $x, @opts );  # Composing argument lists
etc

scalar , ( )?

.

say first( 1, "".second( 'y' ) );    # Side-effect: stringification
say first( 1, 0+.second( 'y' ) );    # Side-effect: numificatiion
say first( 1, !!second( 'y' ) );     # Side-effect: conversion to boolean

Subrountine , .

+4

, :

  • Perl .

  • sub , , . map:

    map { ... } 1, 2, 3; # makes sense
    map { ... } foo();   # can we "return 1, 2, 3" for the same effect?
    

    foo() , return 3, 1, 2, 3. . :

    my @sorted =
      map  { $_->[1] }
      sort { $a->[0] <=> $b->[0] }
      map  { [make_key($_), $_] }
      @input;
    

:

  • , , scalar .

  • ($). , , , . .

+(...) , . (, ) , . map +($_ => 2*$_), 1, 2, 3.

, , .

+7

All Articles