Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpolate hash element via reference returned by a method into a string?

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} 
like image 570
dns Avatar asked Dec 27 '22 04:12

dns


2 Answers

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";
like image 157
friedo Avatar answered Dec 28 '22 18:12

friedo


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";
like image 39
David L. Avatar answered Dec 28 '22 19:12

David L.