1

I have a subroutine that takes the value of $x and gives that value of $a. I can't access the value of $a outside the subroutine, though, since it tells me $a is undefined. I only learned about subroutines yesterday, so I assume there's something about them I'm missing.

sub rout {
  if(@_ == 1) {
    my $a = 3;
  } else {
    my $a = 5;
  }
}

my $x = 1;
rout($x);
print $a;
1
  • Hello, please visit following page related to functions from Modern Perl book. Commented Jul 17, 2021 at 4:46

1 Answer 1

7

First of all, don't use $a and $b. They're a bit special because of their use by sort.


Secondly, @_ == 1 checks the number of arguments provided by the caller. This probably not what you wanted to check. You probably wanted to check the value of the first argument: $_[0] == 1.


The issue is that you are creating a new lexically-scoped variable, assign a value to it, then immediately leave the scope. Your variable is destroyed as soon as you create it! Declare a single variable in the outermost scope where it's needed.

my $y;

sub rout {
  my ($x) = @_;
  if ($x == 1) {
    $y = 3;
  } else {
    $y = 5;
  }
}

my $x = 1;
rout($x);
print "$y\n";

That said, returning a value would make more sense here.

sub rout {
  my ($x) = @_;
  if ($x == 1) {
    return 3;
  } else {
    return 5;
  }
}

my $x = 1;
my $y = rout($x);
print "$y\n";
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe worth mentioning also is that using my $a will not trigger use strict to report a variable out of scope. A subtle error that may stump new users.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.