Title: RE: Subtracting two arrays

The expression @subset{@subset} is a hash slice.

If @subset contained ('one', 'two') then

   @subset{@subset} = ();

is the equivalent of

   @subset{'one', 'two'} = (undef, undef);

or

   $subset{'one'} = undef;
   $subset{'two'} = undef;

Another way of writing

   @subset{@subset} = ();

would be

   $subset{$_} = undef foreach @subset;

In the context of the solution below, the purpose of this is to convert an array into a hash where the array values become the keys of the hash, and where the values of the hash are irrelevant.

This expression would have accomplished the same thing:

    @subset{@subset} = @subset;

That is, a hash where the keys-value pairs are the same.

There's a discussion of hash slices on pp. 129-131 of Professional Perl Programming by Peter Wainwright.

Gary

-----Original Message-----
From: Chuck Lawhorn [mailto:[EMAIL PROTECTED]]
Sent: Friday, September 21, 2001 8:56 AM
To: Perl-Win32-Users; [EMAIL PROTECTED];
'Veeraraju_Mareddi'; [EMAIL PROTECTED]
Subject: Re: Subtracting two arrays


Could you please tell me where I can find out about the syntax of the

@subset{@subset} = ();

line? I see what it does (only by printing out the %subset hash after the line is run), but I
don't think I've ever seen this construction documented. Particularly, how does an item get placed
in a hash by using an lvalue which is a standard array using the @ sign? I also have to start
learning more about and using grep. This is a very elegant solution, and one I would never have
thought of. Thanks, Philip!

--Chuck

--- "Newton, Philip" <[EMAIL PROTECTED]> wrote:

> Oh, you wanted an answer? :) There's one in the FAQ above; here's another
> one:
>
>     # Assume your two arrays are @main and @subset
>     my %subset;
>     @subset{@subset} = ();
>     @main = grep !exists $subset{$_}, @main
>
> Cheers,
> Philip

Reply via email to