Respected Monks,

I am trying an example from Beginning Perl (Curtis Ovid Poe) and in Chapter 5, there's a script about extracting unique values. I'm trying to understanding it, but spectacularly failing. Say I have something like this:

my @array = (1,2,3,4,1,1,3,3,45,54,55); my %unique; @unique{@array} = undef; foreach my $key (sort keys %unique) { print "$key\n"; }

It works as expected, but I don't know why it works. So I checked what perldoc has to say about undef and that still didn't clear it out for me.

I went to the stupid extent of changing @unique{@array} to @something{@array} and the warning made me realize that @unique has to be there because it denotes that it's a slice of the %unique array. But what is it that the undef do to the slice that it doesn't make it throw errors. How does it work? If I remove the undef keyword, I get a warning stating "useless use of hash slice in a void context. I'm just not getting it.

Note: I went through hash slice and there's a paragraph in there that states:

"What happens when you undef a slice is that it is converted into a list, which is then evaluated in scalar context, which yields the last element of the slice as the scalar value. That value (and only that value) is then set to undef (so it's not a no-op; if you want a no-op use the \ operator, which will take a list). Contrast that with handing it an array proper. The entire array is then undefined. The conversion from hash slice to list to scalar is not documented, and should generate a warning. In fact, if you try to pass undef a list of array elements, you will get an error."

I still didn't clearly get it. :(


In reply to What does undef do when I say @hashslice{@array} = undef by pritesh

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.