【问题标题】:What does $$ in perl actually return?perl 中的 $$ 实际上返回了什么?
【发布时间】:2023-03-13 16:12:01
【问题描述】:

我是 Perl 新手,从头开始学习。我读过$$ 返回

运行此脚本的 Perl 进程的 pid。

按照下面的链接,

http://www.tutorialspoint.com/perl/perl_special_variables.htm

我有以下在 Windows 机器上执行的 Perl 脚本,

sub test
{
    my ($surrogate_name) = @_;
    if((defined $surrogate_name) && ($surrogate_name == 1))
    {
        print "Done!"."\n";
    }
    return $surrogate_name;
}

sub t
{
    my ($surrogate_name) = @_;
    my $record;
    my $surrogate_value;
    $record = &test($surrogate_name);
    print $record."\n";
    if ($record)
    {
        print "B"."\n";
        $surrogate_value = $$record{$surrogate_name};
    }
    print $surrogate_value."\n";
    print "A"."\n";
    return $surrogate_value;
}

&t(1);

在这段代码中,我观察到除了$surrogate_value 的值之外的所有内容都被打印出来了。

请澄清$$ 的实际含义以及为什么它没有在我的脚本中返回任何内容。

提前谢谢...

【问题讨论】:

  • 总是use strictwarnings。看起来这里的 $$ 要么是错字,要么是标量取消引用。
  • 您正在阅读哪个教程告诉您使用与符号& 调用子例程,如&test($surrogate_name)?不管是什么,你都应该停止阅读它,因为它已经过时了大约二十年!只是test($surrogate_name) 是正确的。
  • 请不要使用来自tutorialspoint.com的教程。他们很可怕。最好看看learn.perl.orgPerl Tutorial Hub

标签: perl


【解决方案1】:

$$返回当前运行脚本的进程ID。

但在您的情况下,$surrogate_value = $$record{$surrogate_name} 这是一个完全不同的概念,即取消引用。

例如 $$ 与变量名一起使用以取消引用它。

my $a = 10; #declaring and initializing a variable.
my $b = \$a; #taking scalar value reference
print $$b;  #now we are dereferencing it using $$ since it is scalar reference it will print 10

my %hashNew = ("1" => "USA", "2" => "INDIA"); #declaring a hash
my $ref = \%hashNew; #taking reference to hash
print $$ref{2}; #this will print INDIA we derefer to hash here

为了更深入地理解 perl 中的读取引用和解除引用。

【讨论】:

  • 谢谢!它帮助了我... :)
【解决方案2】:

通常 $$ 用于打印当前进程 ID。

print $$;

但是 $ 有另一项工作,用于解除对标量变量的引用。 例如:

use strict;
use warnings;

my $Input = 5;
my $Input_Refer = \$Input;
print "$Input\n";
print $$Input_Refer;

在上面的例子中,我们有两个标量变量, 1. $Input,其中包含 5 作为值。 2. $Input_Refer,它包含一个 $Input 变量的引用作为值。 所以如果我们打印$Input,它的值为5, 如果我们打印$Input_Refer,它将打印$Input的内存地址。 所以我们必须取消引用它,为此我们必须像这样使用另一个 $,

print $$Input_Refer;

它将输出为 5。

【讨论】:

    【解决方案3】:

    变量$$,正如你所写,是当前进程的PID:

    print $$ . "\n";
    

    你在脚本中写的是$$record{$surrogate_name},这意味着访问一个哈希元素,相当于$record->{$surrogate_name}

    除此之外,$$name 通常意味着取消对标量的引用。例如,如果您有:

    my $x = 1;    # Scalar
    my $y = \$x;  # Scalar, value of which is a reference to another scalar (address)
    my $z = $$y;  # Dereference the reference, obtaining value of $x
    

    相当于对C中的指针进行如下操作:

    int  x = 1;
    int *y = &x;
    int  z = *y;
    

    阅读更多关于here的信息。

    【讨论】:

    • 这是不正确的。 $$record 本身是 “对标量的引用的取消引用”,当然,但在上下文中 $$record{$surrogate_name} 是通过对哈希的引用访问哈希元素,并且与 @ 相同987654332@.
    猜你喜欢
    • 2012-11-11
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多