Mohammad Basit
Mohammad Basit

Reputation: 575

I want to access private variable of a subroutine outside it

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

Answers (1)

H&#229;kon H&#230;gland
H&#229;kon H&#230;gland

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

Related Questions