|The stupid question is the question not asked|
Re: Is it safe to use join on a hash?by davido (Cardinal)
|on Sep 07, 2020 at 01:08 UTC||Need Help??|
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.
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.
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.
What do you think @un_nums contains now? It contains a single element. $un_nums contains a string: "17 10 20 33 30 40 15 16" (but with its numbers in unpredictable order). There is no $un_nums, or beyond. Only a single element. Of what use is that?
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:
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).