David92 has asked for the wisdom of the Perl Monks concerning the following question:

Hello respectfull Monks,

I seek for your wisdom. I have been stucked with a problem with Hashes.

I have a hash, for example: testHash{$year}{$status} = ..some value..

There are many different statuses that I have (it is not a fix number). The number changes when I refresh the PERL script, which fetches the data from database.

I am writting a File with PERL, and it requires that I have to delete the last character (",") in my file. But before, I need the "," in my file at the end of each sentence.

So Id like to get the size of the hash second Key, not the first one (I know how to do that one). When I have the size, I can loop around until I reach the last key and then delete the "," from the last sentence in my generated file.

Can anyone help me please?

BR, David

Replies are listed 'Best First'.
Re: Size of a HASH (with more keys)
by choroba (Cardinal) on Jul 02, 2014 at 12:02 UTC
    Use keys in scalar context:
    my $count = keys %{ $testHash{$year} }

    It might be better not to output the comma, though. Just invert the logic and print it before each sequence except the first one which is easy to detect:

    my $first = 1; while (...) { print ',' unless $first; undef $first; print "..."; # print the sentence }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      I tried using your suggestion, but it didnt work. I am onto debugging, if something's wrong before with the Hash.
Re: Size of a HASH (with more keys)
by perlfan (Parson) on Jul 02, 2014 at 12:08 UTC
    This thing about the comma bothers me, maybe I don't get what your're doing or why you require a comma before you delete it (just sounds wrong and brittle). Should you be using a join? This'll make sure that your separator is not added at the end of the last item in the list.

      I apologize for lack of information / explanations.

      What I'm doing:

      I am creating a Hash that will store the certain data from a database. And then I need to use that Hash's data to create a JSONP file format.

      JSONP format requires certain structure: http://en.wikipedia.org/wiki/JSONP

      That is why I need to remove the comma at the end of the last sentence, otherwise my .HTML file wont recognize it as valid JSONP file.

      Hope it is more clear now.

      BR, David
        > Hope it is more clear now.

        nope

        But ...

        > I am creating a Hash that will store the certain data from a database

        ... and ...

        > ... remove the comma at the end of the last sentence

        don't fit together, because hashes have no order.

        see also How (Not) To Ask A Question and How do I post a question effectively?

        Cheers Rolf

        (addicted to the Perl Programming Language)