gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:13:05 25 4
gpt4 key购买 nike

我试图在子例程之外访问子例程的私有(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com