develooper Front page | perl.beginners | Postings from February 2002

"Learning Perl" Question

Thread Next
Hanson, Robert
February 13, 2002 08:06
"Learning Perl" Question
Message ID:
[Sorry if this isn't the place to post this, but I thought it might be
interesting.  Flaming will be accepted]

I'm teaching a Perl class from the Learning Perl book, and noticed an
inconsistency with the way certain constructs work.

In chapter 2 it mentions a rule in Perl: "any time that you need a variable
in Perl, you can use an assignment instead.  First, Perl does the
assignment.  Then it uses the variable in whatever way you requested".

Ok, that makes sense.  It allows you to do things like this:

chomp( $foo = <STDIN> );
$x = $y = 10;

Then in chapter 5 it discusses the each function, and why it works in a
while loop.  It says that (referring to the boolean value) "Now, when Perl
evaluates the each %hash there are no more key-value pairs available.  So
each has to return an empty list.  The empty list is assigned to ($key,
$value), so $key gets undef, and $value also gets undef.  But that hardly
matters, because the whole thing is being evaluated in the conditional
expression of the while loop.  The value of a list assignment is a scalar
context is the number of elements in the **source list** -- in this case,
that's 0".

So this adds to the first rule (sort of).  Basically in scalar context the
function takes the variable as it's argument, and in list context it takes
the count of items in the source list.

....Ok, that works for me so far, but then why would these work?

$x = () = 10; # $x is 1
$x = () = (10, 20); # $x is 2

From this it sounds like the first rule does not exactly work as stated.  It
seems that the real rule is that the "=" operator returns a value just like
any other Perl operator.  It seems to me that given "x = y" that the "="
operator returns the value from the right side of the operator (in the given
context of x).

So "x = y = z" means that "y = z" returns the value of z, and then "x = "
stores that value. ...Or at least that is how I am conceptualizing it.

....And now the real question.  Why won't this work?

($x) = () = 10;

Is there a need for an extra rule to cover this?  Or is there a single rule
that covers the syntax from all of the above examples?



Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About