Reputation: 575
I am trying to access private variable of subroutine outside the subroutine. How to do this?
I tried the code i have posted with the question but it is printing the values of global variable "name" and the condition is that the name of the global variable and the private variable has to be the same.
print("Please Enter Your First Name:\n");
# declaration of global variable
$name = <>;
YourFirstName_StudentID($name);
sub YourFirstName_StudentID {
print("My name is $name\n");
print("Enter Your Student ID\n");
my $name = <>;
}
#printing outside subroutine
print("Student Id is: $name");
Output currently is: Please Enter Your First Name: My name is xyz
Enter Your Student ID Student Id is: xyz
But i want it like this Please Enter Your First Name: My name is xyz
Enter Your Student ID Student Id is: 1234567
Upvotes: 1
Views: 111
Reputation: 40778
Here is an example, we don't need to use global variables here. It is better to use lexical variables:
use strict;
use warnings;
{ # <--- Make a scope so lexical variables do not leak out into
# subs declared later in the file..
print("Please Enter Your First Name:\n");
chomp (my $name = <>);
my $id = YourFirstName_StudentID($name);
print("Student Id is: $id\n");
}
sub YourFirstName_StudentID {
#print("My name is $name\n");
print("Enter Your Student ID\n");
chomp( my $id = <>);
return $id; # <--- return local variable to caller
}
Upvotes: 5