Rob Rob - 5 months ago 18
Perl Question

Perl: Variable is printed as SCALAR(0x7faf2b804240)

I have a variable that performs well in one section of my code, but not in another. I will attempt to truncate my very long code to give you an idea of what is going on. I will name the variable in question simply "$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;


Now I will omit the long subroutines for readability's sake. I am assuming they won't help in solving this problem, since I believe they produce my expected output without error. $QuestionableVariable works well in the above section of code but below I will show you the end of my program, after the appearance of the subroutines, where it does not work well.

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


The code runs without error, but in place of the value of $QuestionableVariable I get SCALAR(0x7faf2b804240).
How can I get the value of the variable instead?
Thanks

Answer

Your "working" line uses $$QuestionableVariable, not $QuestionableVariable.

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

Bad assumption. Apparently LongSubroutine returns a reference to a scalar, not a plain string. That's why you get SCALAR(0x7faf2b804240) as output: That's what references look like when printed.

$$QuestionableVariable dereferences the reference to get at the contents, which seems to be working fine.

If you change your last line to

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

it should work as you expect.