Perl:变量打印为 SCALAR(0x7faf2b804240)

Perl: Variable is printed as SCALAR(0x7faf2b804240)

我有一个变量在我的代码的一部分中表现良好,但在另一部分中表现不佳。我将尝试截断我很长的代码,让您了解发生了什么。我将简单地将有问题的变量命名为“$QuestionableVariable”。

    #!/usr/bin/perl 
    use warnings; 
    use strict;  

    my $QuestionableVariable = LongSubroutine("file.txt"); 
    my $WindowSize = 16; 
    my $StepSize = 1; 
    my %hash = (); 

    for ( 
            my $windowStart = 0; 
            $windowStart <= 140; 
            $windowStart += $StepSize 
    ) 
    { 
    my $Variable_1 = substr($$QuestionableVariable, $windowStart, $WindowSize); #here $QuestionableVariable works well 
    my $Variable_2 = 'TAGCTAGCTAGCTAGC'; 
    my $dist = AnotherLongSubroutine($Variable_1, $Variable_2); 
    $hash{$dist} = $Variable_1; 

现在为了便于阅读,我将省略较长的子程序。我假设他们不会帮助解决这个问题,因为我相信他们会毫无错误地产生我预期的输出。 $QuestionableVariable 在上面的代码部分运行良好,但下面我将向您展示我的程序的结尾,在子例程出现之后,它运行不佳。

    my @keys = sort {$a <=> $b} keys %hash; 
    my $BestMatch = $hash{keys[0]}; 

    print "Distance_of_Best_Match: $keys[0] Sequence_of_best_match: $BestMatch", "\n", "$QuestionableVariable", "\n";  

代码运行没有错误,但我得到的是 SCALAR(0x7faf2b804240) 而不是 $QuestionableVariable 的值。 我怎样才能得到变量的值呢? 谢谢

您的 "working" 行使用 $$QuestionableVariable,而不是 $QuestionableVariable

Now I will omit the long subroutines for readability's sake. I am assuming they won't help in solving this problem

错误的假设。显然 LongSubroutine returns 是对标量的引用,而不是纯字符串。这就是为什么您得到 SCALAR(0x7faf2b804240) 作为输出的原因:这就是打印时引用的样子。

$$QuestionableVariable 取消引用以获取内容,这似乎工作正常。

如果您将最后一行更改为

print "Distance_of_Best_Match: $keys[0] Sequence_of_best_match: $BestMatch\n", "$$QuestionableVariable\n";

它应该如您所愿地工作。