It is not uncommon that a parameter is passed a few times.
Here is an interesting example of losing the quote can actually helps.
The first abs() return a variable without quote, making the second abs return the correct value.
My question is:
Does perl have an internal function to unquote a variable so that I do not have to code this way?
#!/usr/bin/perl -w
use strict;
my @nums = (
'-0',
'-0.0',
"-0.000",
qw(-0.000),
sprintf("%.4f", "-0.0"),
);
print "***use single abs()\n";
foreach my $num(@nums){
my $number = $num;
my $abs = abs($number);
print "<$num> abs <$abs>\n";
}
print "\n***use abs(abs())\n";
foreach my $num(@nums){
my $abs_abs = abs(abs($num));
print "<$num> double abs <$abs_abs>\n";
}
System information:
uname -r
2.6.32-573.12.1.el6.centos.plus.x86_64
This is perl, v5.10.1 (*) built for x86_64-linux-thread-multi
The screen output:
***use single abs()
<-0> abs <0>
<-0.0> abs <-0>
<-0.000> abs <-0>
<-0.000> abs <-0>
<-0.0000> abs <-0>
***use abs(abs())
<-0> double abs <0>
<-0.0> double abs <0>
<-0.000> double abs <0>
<-0.000> double abs <0>
<-0.0000> double abs <0>
That's not an issue with quotes -- the quotes are just Perl syntax to tell the interpreter where a string begins and ends. Perl knows that the value being stored is a string, but the quotes themselves are not stored in memory.
Rather, it's an artifact of the special floating point value "-0.0". For almost any use, it is equivalent to the value 0.0
perl -E ' $p = 0.0; $n = -0.0; say $p == $n ' ==> 1
perl -E ' $p = 0.0; $n = -0.0; $x = 4.2; say $p+$x == $n+$x ' ==> 1
The two exceptions, as far as I can tell, are their binary representation and their string representation.
$ perl -e 'print pack "F",0.0' | od -c
0000000 \0 \0 \0 \0 \0 \0 \0 \0
0000010
$ perl -e 'print pack "F",-0.0' | od -c
0000000 \0 \0 \0 \0 \0 \0 \0 200
0000010
$ perl -MDevel::Peek -e 'Dump($n=-0.0),Dump($p=0.0)'
SV = NV(0x43523d8) at 0x434ff00
REFCNT = 1
FLAGS = (NOK,pNOK)
NV = -0
SV = NV(0x43523e0) at 0x4329b58
REFCNT = 1
FLAGS = (NOK,pNOK)
NV = 0
$ perl -E '$p=0.0; $n=-0.0; say for $p,$n'
0
-0
(actually, with Perl v5.12 I see 0,-0
but with v5.16 it is 0,0
-- maybe somebody noticed this and fixed it)
The integers 0
and -0
do not have this issue.
abs(-0.0)
returns the integer 0, and so it really by accident that abs
appears to resolve this "quoting" issue.
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