Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Cannot get {{{ "bar", "baz", "foo" }}} to set as { "bar", "baz", "foo" }

Perl functions can be invoked in two contexts: list and scalar. These contexts indicate what is to be done with the return value. Functions can return different values in list context than in scalar context. For instance, the grep() function takes a list and a block or expression , and filters out elements of the list for whom which the block or expression evaluates to false. The grep() function returns the filtered list when called in list context, but when called in scalar context, it merely returns the size of this list. That is, it returns the number of elements for whom the whichthe block or expression evalues evaluates to true.

Some functions do not define what they return in list or scalar context. For instance, according to the {[perlfunc}} manpage, the sort() function "sorts the LIST and returns the sorted list value. In scalar context, the behaviour of "'sort()" ' is undefined.".

Noncompliant Code Example (sort())

This noncompliant code example inadvertantly inadvertently assigns a scalar to the result of the sort() function.

...

The contents of $result are undefined , because the sort() function's return value is not defined in a scalar context.

...

This compliant solution guarantees that the ret() function is called only called in list context.

Code Block
bgColor#ccccff
langperl
sub ret {
  my $list = shift;
  my @list = @{$list};
  # ...
  return sort @list;
}

my @list = ( "foo", "bar", "baz");
my @result = ret @list;

...