Cool/useful short examples of Perl?

Nicholas Clark nick at ccl4.org
Thu Jun 9 10:40:14 BST 2011


On Thu, Jun 09, 2011 at 10:26:22AM +0100, Matt Lawrence wrote:
> On 08/06/11 18:19, Philip Newton wrote:
> >On Wed, Jun 8, 2011 at 15:37, Matt Lawrence<matt.lawrence at virgin.net>  
> >wrote:
> >>Perl's canonical true and false are 1 and '' respectively
> >Is that so? How would one find that out?
> >
> >Dump-ing 4==4 and 4==5 with Devel::Peek implies to me that true and
> >false are PVNVs with integer, floating-point, and string values filled
> >simultaneously, so I'm not sure how any of the three fields could be
> >considered "the" value of those, er, values(?).
> 
> Isn't that true of all scalars, under the hood? All I meant was:
> 
> $ perl -le 'print "\x27$_\x27" for 1 == 1, 1 == 0'
> '1'
> ''

"truth" has a value, and it's consistent with any other "1" that's been used
in an integer, floating point and string context:

$ perl -MDevel::Peek -e '$a = 1; sprintf "$a%g", $a; Dump $a; Dump 1 == 1'
SV = PVNV(0x1008031a0) at 0x100811948
  REFCNT = 1
  FLAGS = (IOK,NOK,POK,pIOK,pNOK,pPOK)
  IV = 1
  NV = 1
  PV = 0x100201790 "1"\0
  CUR = 1
  LEN = 16
SV = PVNV(0x100802c20) at 0x100800828
  REFCNT = 2147483643
  FLAGS = (IOK,NOK,POK,READONLY,pIOK,pNOK,pPOK)
  IV = 1
  NV = 1
  PV = 0x100200090 "1"\0
  CUR = 1
  LEN = 16

It's falsehood which is special:

$ perl -MDevel::Peek -MScalar::Util=dualvar -e '$a = dualvar(0, ""); sprintf "%g", $a; Dump $a; Dump 0 == 1'
SV = PVNV(0x100803a40) at 0x100815418
  REFCNT = 1
  FLAGS = (IOK,NOK,POK,pIOK,pNOK,pPOK)
  IV = 0
  NV = 0
  PV = 0x1002017c0 ""\0
  CUR = 0
  LEN = 16
SV = PVNV(0x100802c00) at 0x100800810
  REFCNT = 2147483647
  FLAGS = (IOK,NOK,POK,READONLY,pIOK,pNOK,pPOK)
  IV = 0
  NV = 0
  PV = 0x100200080 ""\0
  CUR = 0
  LEN = 16


It's effectively a dualvar with a string value of an empty string, and a
numeric 0.

(Yes, an empty string has the value of 0 when used in a numeric context, but
it warns about the conversion. The dualvar doesn't)

[whilst beer is foamy, and none of the above]

Nicholas Clark


More information about the london.pm mailing list