in reply to Re: All array elements the same?
in thread All array elements the same?

Okay, you threw me on this one. Could someone please explain the above code. I am completely lost!

```J. J. Horner
Linux, Perl, Apache, Stronghold, Unix
jhorner@knoxlug.org http://www.knoxlug.org/
```

Replies are listed 'Best First'.
RE: RE: Re: All array elements the same?
by davorg (Chancellor) on Aug 01, 2000 at 20:39 UTC

It does the job tho' :)

```# define a hash to count the unique elements in @arr
my %check;

# @check{@arr} is a hash slice. It gives to all of the
# values in %check where the key is an element from @arr.
# This is a list and it's also an lvalue (i.e. you can
# assign values to it.
#
# (1) x @arr (and I've corrected this from the original
# version. Uses the 'x' operator as a list constructor.
# In a list context it creates a list containing its
# left operand repeated the number of times given by
# the right operand (which is a scalar). @arr in a scalar
# context gives the number of elements in @arr. Hence
# we get a list containing scalar(@arr) 1s.
#
# We then assign this list to the list of lvalues created
# by @check{@arr}. This assigns a 1 to each value associated
# with a key found %check. The keys of %check are given by
# @arr, therefore we effectively create a key/value pair
# in %check for each element of @arr where the key is the
# element of @arr and the value is 1. If any element of
# @arr occurs multiple times we assign to the relevant
# value in %check multiple times.
#
# We can then use 'keys' to extract this list of keys. If
# all the elements of @arr are the same the list of keys
# in %create only has one element.

@check{@arr} = (1) x @arr;

print "All the same" if keys %check == 1;

Does that help?</code> --
<http://www.dave.org.uk>

European Perl Conference - Sept 22/24 2000, ICA, London
<http://www.yapc.org/Europe/>

RE:(3) All array elements the same? (Code explained)
by Russ (Deacon) on Aug 01, 2000 at 20:34 UTC
He's putting all the elements of the array into a hash, using a hash slice @check{@arr} = @arr x 1;

Then, if there is only one key, all the values must have been identical.

@check{@arr} is the "keys" part of the slice, and @arr x 1 just gives us the correct number of "values."

Voila! A list of the unique elements of @arr (in keys %check). If there is only one unique element, then they are all the same. Two problems solved for the price (two lines, in this case) of one. :-)

Russ
Brainbench 'Most Valuable Professional' for Perl

I see now. Apparently I don't have enough caffeine.

It was the @hash{@array} thing that threw me. Don't see that often and have never used it.

```J. J. Horner
Linux, Perl, Apache, Stronghold, Unix
jhorner@knoxlug.org http://www.knoxlug.org/
```