$i = 5;
print "{$i*10}";
Sometimes I may need to do things like above,but Perl doesn't interpret it the way I want,and I can only do it with another variable.Is there a trick?
$i = 5;
print "${\($i*10)}";
or
print "@{[$i*10]}";
These interpolate a "variable" that is a dereference of a code block that contains a reference of the appropriate type (scalar in the first instance, array in the second).
Another way would be to have a dummy hash that always returns the key as a value:
use strict;
use warnings;
{
package Tie::Hash::Dummy;
use Tie::Hash;
use parent -norequire => 'Tie::StdHash';
sub FETCH { $_[1] }
tie our %Lookup, __PACKAGE__;
}
my $i = 5;
print "$Tie::Hash::Dummy::Lookup{$i*10}";
Another way would be to use the \N{}
character name lookup interface, though this will bind variables from a different location, and at compile time (as well as using string eval, potentially a security issue):
my $i;
BEGIN { $i = 5 }
BEGIN { $^H{'charnames'} = sub { eval $_[0] } }
print "\N{$i*10}";
(This might work better if the charnames handler returned an overloaded proxy object that performed the eval upon stringification, but I don't have time to try it.)
Yet another way would be to set a string-constant handler with overload::constant().
I suggest you use "printf":
printf("%s",$i*10);
That'll do.
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