int(rand() + 1), int(rand()) +1, and hashes

Eugene Tsyrklevich eugene at
Sun Jul 16 02:30:58 CDT 2000

On Sat, Jul 15, 2000 at 11:05:58PM -0700, C. Abney wrote:
> ~sdpm~
> This is just plain wierd.  Why should adding an integer and a float be faster
> than adding two integers? The only difference betweeen sub randint1 and
> randint2 below is that int() is applied after 1 is added to the output of
> rand() in randint1, but int is applied to rand() before the addition in
> randint2.  This behavior is specific to hashes (not arrays) so I think there's
> some heavy magic going on in the background.  Someone mentioned to me that
> floats used as array indexes will be automagically truncated by Perl, and
> it's possible this perk has masked a bug revealed in the hash example?
> Anybody have any ideas (sorry about the labeling problem, below)?

$ perl -wle '$h{1.005}=1; $,=" - "; print each %h'
1.005 - 1

A floating number 1.005 is converted into a string and is used as a hash key.
Converting a floating number to a string is obviously much slower than
converting an int

what's so surprising?

bash-2.03# perl -wle 'use Devel::Peek; $a=5; Dump($a)'
SV = IV(0xf40c) at 0x6f18
  REFCNT = 1
  IV = 5
bash-2.03# perl -wle 'use Devel::Peek; $a="5"; Dump($a)'
SV = PV(0x640c) at 0x6f18
  REFCNT = 1
  PV = 0x50a0 "5"\0
  CUR = 1
  LEN = 2
bash-2.03# perl -wle 'use Devel::Peek; $h{1.005}=1; Dump +(keys %h)[0]'
SV = PV(0x640c) at 0x6ee8
  REFCNT = 1
  PV = 0x5c20 "1.005"\0
  CUR = 5
  LEN = 6
bash-2.03# perl -wle 'use Devel::Peek; $h{1.005}=1; Dump +(values %h)[0]'
SV = IV(0xf404) at 0x6ee8
  REFCNT = 1
  IV = 1

The posting address is: san-diego-pm-list at

List requests should be sent to: majordomo at

If you ever want to remove yourself from this mailing list,
you can send mail to <majordomo at> with the following
command in the body of your email message:

    unsubscribe san-diego-pm-list

If you ever need to get in contact with the owner of the list,
(if you have trouble unsubscribing, or have questions about the
list itself) send email to <owner-san-diego-pm-list at> .
This is the general rule for most mailing lists when you need
to contact a human.

More information about the San-Diego-pm mailing list