I want to interpolate hash reference to string, but this method is not working.
How does one interpolate $self->Test->{text}
?
# $self->Test->{text} contains "test 123 ok"
print "Value is: $self->Test->{text} \n"; # but not working
output:
Test=HASH(0x2948498)->Test->{text}
Method calls won't get interpolated inside double quotes, so you end up with the stringified reference followed by ->Test->{text}
.
The simple way to do it is to take advantage of the fact that print
takes a list of arguments:
print "Value is: ", $self->Test->{text}, "\n";
You could also use concatenation:
print "Value is: " . $self->Test->{text} . "\n";
You could also use the tried-and-true printf
printf "Value is %s\n", $self->Test->{text};
Or you can use this silly trick:
print "Value is: @{ [ $self->Test->{text} ] }\n";
See https://perldoc.perl.org/perlfaq4.html#How-do-I-expand-function-calls-in-a-string%3F
For your example the best matching form would be in my opinion:
print "Value is: ${ \$self->Test->{text} } \n";
The question is the added value of the interpolation? It is supposed to be quicker then concatenation but based on http://perl.apache.org/docs/1.0/guide/performance.html#Interpolation__Concatenation_or_List the difference is very small and the quickest way, in this particular print context, is:
print "Value is: ", $self->Test->{text}, " \n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With