"Advanced" functions

context and wantarray

Perl has three contexts: void,scalar and list.

  1. func(); # void
  2. my $ret = func(); # scalar
  3. my ($ret) = func(); # list
  4. my @ret = func(); # list

If you're in a subroutine or eval block, you can use wantarray to determine which is wanted.

An example of where context affects return values is in dealing with regular expressions:

  1. my $str = 'Perl 101 Perl Context Demo';
  2. my @ret = $str =~ /Perl/g; # @ret = ('Perl','Perl');
  3. my $ret = $str =~ /Perl/g; # $ret is true

.. and …

These are called the range operators, and they can help with code that deals with ranges of integers or characters.

In the previous example, @array was filled by hand. But these are equivalent:

  1. my @array = ( 0, 1, 2, 3, 4, 5 );
  2. my @array = 0..5;

Oddly enough, it works with characters, too. If you want to get a list of letters from a to z, you can do:

  1. my @array = 'a'..'z';

When used in this way, .. and are equivalent

The range operators only increment. This will produce a zero-size list:

  1. my @array = 10..1; # @array is empty

If you want the reverse, ask for it.

  1. my @array = reverse 1..10; # @array descends from 10 to 1

You can also use the range operator in a scalar context, but that is outside the scope of this presentation. Check the man page for more details.


Want to contribute?

Submit a PR to github.com/petdance/perl101