perl - 我想访问子程序外部的私有(private)变量

标签 perl

我试图在子例程之外访问子例程的私有(private)变量。如何做到这一点?

我尝试了我发布的问题代码,但它正在打印全局变量“名称”的值,并且条件是全局变量和私有(private)变量的名称必须相同。

 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");

当前输出为: 请输入您的名字: 我的名字是xyz

输入您的学生证 学生ID是:xyz

但我想要这样 请输入您的名字: 我的名字是xyz

输入您的学生证 学号是:1234567

最佳答案

这是一个例子,这里我们不需要使用全局变量。最好使用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
}

关于perl - 我想访问子程序外部的私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57039624/

相关文章:

perl - 为什么 '$_' 与 Perl 单行代码中的 $ARGV 相同?

perl - 我如何让 Perl::Critic 与 E.P.I.C 和 eclipse 一起工作?

regex - 如何在perl中使用正则表达式在字符的第一个实例而不是最后一个实例处停止.+?

java - 什么是操作 Apache2 配置文件的好库?

perl - 驼鹿属性 : separating data and behaviour

perl - 为什么这两种确定打印列数的方法表现不同?

Perl 嵌套结构

mysql - Perl 解析和重建 MySQL Schema

linux - revbeal 密码输入字段的 HTML 按钮

perl - 在 Path-Class-Dir 模块中创建目录树