pritesh has asked for the wisdom of the Perl Monks concerning the following question:
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. :(
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: What does undef do when I say @hashslice{@array} = undef
by Corion (Patriarch) on Nov 05, 2014 at 09:58 UTC | |
by pritesh (Scribe) on Nov 05, 2014 at 10:30 UTC | |
by Athanasius (Archbishop) on Nov 05, 2014 at 14:17 UTC | |
by pritesh (Scribe) on Nov 05, 2014 at 18:18 UTC | |
|
Re: What does undef do when I say @hashslice{@array} = undef
by Anonymous Monk on Nov 05, 2014 at 09:52 UTC |