How to Pass Parameters to Subroutines in Perl

104 2
    • 1). Open a Perl program file. Type the following code:

      sub line {

      $var = @_[0];

      }

      This subroutine uses the "@_" array to get the parameters, but only makes use of the first one. Calling either "line('Hello!');" or "line('Hello!', 'How are you?');" both print "Hello!" to the screen.

    • 2). Type the following code:

      sub addNums {

      $total = 0;

      for ($i = 0; $i < @_; $i++) {

      $total = $total + @_[$i];

      }

      return $total;

      }

      This subroutine call makes use of all the parameters passed to it, regardless how many exist. Calling "addNums(2,3);" returns five, "addNums(2,5,3);" returns 10 and "addNums(6,2,4,4);" returns 16.

    • 3). sub array {

      local($parOne, $parTwo, $parThree);

      ($parOne, $parTwo, $parThree) = ($_[0], $_[1], $_[2]);

      print "You passed $parOne, $parTwo and $parThree as parameters.";

      }

      This subroutine takes the first three parameters passed to it and assigns them to local variables. Using specific variable names in longer subroutines can make it easier to understand what each is for instead of using the generic @_ array.

    • 4). Save the Perl program file and run it.

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.