Perl: Function Optional Parameter

By Xah Lee. Date: . Last updated: .

Here is a example of a function.

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;
$Data::Dumper::Indent = 0;      # print in compact style

# define a function
sub ff {
  $a = $_[0]; # get first arg
  $b = $_[1]; # get second arg

  # arguments are automatically assigned to array @_
  print Dumper(\@_);            # prints the array @_

  # use “return” to return value and exit function
  return $a + $b;
}

ff(3, 4, "rabbit");             # $VAR1 = [3,4,'rabbit'];

Note: Unlike most other languages, perl subroutine's parameters are usually not declared.

Arguments are automatically assigned to the array @_. So, $_[0] is the first element of the array @_. The @_ array is a predefined array.

Optional Parameters

To define a function with optional parameters, just use defined($_[n]) to check if the argument is given.

# -*- coding: utf-8 -*-
# perl

# myFun(x,y) returns x+y. y is optional and default to 1.
sub myFun {
  $x = $_[0];

  if (defined $_[1]) {
    $y = $_[1];
  } else {
    $y = 1;
  }

  return $x+$y;
}

print myFun(3);                 # 4

perldoc perlsub

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex
  14. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. List Modules, Search Paths
  4. Write a Module
  5. Read / Write File
  6. Traverse Dir
  7. Find / Replace
  8. Complex Numbers
  9. System Call
  10. Compress / Decompress gzip
  11. Get Env Var
  12. GET Web Content
  13. Unicode 🐪
  14. Convert File Encoding
  15. Sort Unstable