-2

I am trying to write a subroutine to demonstrate getting a subroutine of a number as a function in Perl. I have no idea how to use the @_ operator in perl

#!/usr/bin/perl
use strict ;
use warnings ;
my $number = $ARGV[0] ;
if (not defined $number) {
        die " I need a number to multiply" }

    sub square {
        my $number = shift ;
        print "$number\n"
        return $number * $number ;
}

my $result = square() ;
print "$result";
capser
  • 2,442
  • 5
  • 42
  • 74
  • See the beginning ("Description") in [perlsub](https://perldoc.perl.org/perlsub.html), and your favorite introductory book. – zdim Nov 26 '18 at 17:49

2 Answers2

2

Your subroutine expects a number as first argument. You access the argument when you do :

my $number = shift;

Which is actually roughly equivalent to :

my ($number) = @_;

So as you can see, @_ is a special variable that represents the list of arguments that were passed to the subroutine.

The problem in your code is that you do not pass any argument to your sub. This :

my $result = square();

Should be written as :

my $result = square($number);
GMB
  • 216,147
  • 25
  • 84
  • 135
2

You are not passing $number to your sub. Try this:

#!/usr/bin/perl

use strict ;
use warnings ;

my $number = $ARGV[0] ;

die "I need a number to multiply" unless(defined $number);

sub square {
    my $number = shift ;
    print "$number\n";
    return $number * $number;
}

my $result = square($number);
print "$result\n";
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108