http://qs321.pair.com?node_id=11121427


in reply to Is it safe to use join on a hash?

Consider what you're doing. Perl is perfectly capable of using join on any list, including a list of hash keys. But that doesn't mean that your usage actually makes a whit of sense.

my @nums = (17, 10, 20, 33, 30, 40, 10, 33, 40, 15, 16, 17);

Here you have an array with the following elements: 17, 10, 20, 33, 30, 40, 10, 33, 40, 15, 16, 17. The number of elements in the array is 12.

my %unordered = map { $_ => undef } @nums;

Now you have a hash of key/value pairs where the keys are comprised of the elements that are in the @nums array. Except for one problem? 17 is repeated twice. 10 is repeated twice, 33 is repeated twice. 40 is repeated twice. Hash keys can only be unique. Duplicates replace previous instances. So now the keys are: 17, 10, 20, 33, 30, 40, 15, 16. So there are now 8 hash elements.

my @un_nums = join " ", keys %unordered;
What do you think @un_nums contains now? It contains a single element. $un_nums[0] contains a string: "17 10 20 33 30 40 15 16" (but with its numbers in unpredictable order). There is no $un_nums[1], or beyond. Only a single element. Of what use is that?

print "@un_nums\n";

Now this is funny: if @un_nums contained eight elements, or only one element that consists of a single string of eight numbers, the output here will be the same because by default the list separator $" is a single space by default (see perlop). Of course you're not invoking the list separator because your array contains only a single element. But what I'm saying is this:

my @array1 = (1, 2, 3, 4, 5); my @array2 = ("1 2 3 4 5"); print "@array1\n"; print "@array2\n";

These two will produce identical output.

There's nothing wrong with using join on hash keys, nor is there anything wrong with using join to construct an element of an array. But it looks a lot like you're using it mistakenly in this case. Otherwise, why would you have assigned the string to @un_nums instead of $un_nums?

So the effect of your code is to take a list of 12 elements, boil it down to a list of 8 unique elements in no particular order, and then convert those elements to a string, and store that string in the first (and only) element of an array. Then print all the elements of that array (of which there is only one; a string of 8 unique numbers in whatever order they ended up being placed in the string).


Dave

Replies are listed 'Best First'.
Re^2: Is it safe to use join on a hash?
by pritesh_ugrankar (Monk) on Sep 07, 2020 at 18:50 UTC
    Hi David, Thanks. And I forgot to mention but I wanted to extract unique elements only. Still, your answer clears a lot of doubts.
    Thanks once again.

      The keys returned by keys are unique. The keys of a hash are always unique.


      Give a man a fish:  <%-{-{-{-<

        The keys returned by keys are unique. The keys of a hash are always unique.

        Nitpick: Except for tied hashes :-)