Thread: Object Size

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2011
    Posts
    53
    Rep Power
    3

    Object Size


    Will:
    Code:
    $hash_size = %object
    Give me the amount of hash elements in an oject?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,875
    Rep Power
    1225
    What did you learn when you tested it?
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2011
    Posts
    53
    Rep Power
    3
    That I needed to use a reference.

    Code:
    $size = %$object;
    print "$size";
    Gives me 4/8 for my objects with 5 elements.
    I get 4/8 for my objects with 7 elements.
    I get 6/16 for my objects with 9 elements.

    Basically I'm going to create a subroutine that uses my object data to get more data. I'm trying to decide if I should package all 3 objects into one array and pass it into one sub routine by reference (this would require me being able to identify the 3 different objects and I was thinkning I could do this by finding out how many hash elements each object has). For my smallest object I'd need one pass through the sub, for my 2nd largest object I'd need 2 passes and for my largest object I'd need 3. It may be easier to just create 3 subs or pass in a references to all 3 objects instead of an array.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2011
    Posts
    53
    Rep Power
    3
    Got it

    Code:
    $size = keys %{$hash};
    I think I've made a huge mistake learning about objects before I fully understand hashes.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    776
    Rep Power
    495
    Yes, if you were looking for the numbers of elements of your hash, you got it right: using the keys funtion on the hash in a sclarar context just gives you that.

    And by the way, it appears from a discussion on another forum today that Perl does not need to actually build the array of keys to report the size of the hash. You can verify this with, for example, the following commands on the Perl debugger:

    Perl Code:
      DB<3> $h{$_}=1 foreach 0..30000000
     
      DB<4> print scalar keys %h
    30000001
      DB<5>


    (You may have to adapt the size of your hash depending on the memory available on your computer, I have 8 GB.)

    On my computer, building the 30 M element hash (line 3) takes about 34 seconds. But printing the size (line 4) takes only a split second. It seems that Perl detects that the only thing that is looked for is the size of the hash, and somehow shortcuts the evaluation of the array of keys.

IMN logo majestic logo threadwatch logo seochat tools logo