Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl,is there a way to do simple arithmetic inside quotes?

Tags:

perl

$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?

like image 305
Learning Avatar asked Nov 28 '22 22:11

Learning


2 Answers

$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().

like image 84
ysth Avatar answered Dec 20 '22 04:12

ysth


I suggest you use "printf":

printf("%s",$i*10);

That'll do.

like image 41
Nodebody Avatar answered Dec 20 '22 04:12

Nodebody