--- "McCormick, Rob E" <[EMAIL PROTECTED]> wrote:
>
> I'm trying to understand an example from the Waite Press book (Perl 5
> Interactive Course, a bit dated, '97, Orwant) The example doesn't
> have -w or strict; enabled. I ran it with them and the error
follows:
>
> #!c:/perl/bin/perl -w
> use strict;
>
> print "Please type an integer: ";
> chomp ( my $num = <STDIN>);
> while ( $num != 1 ) {
> print "$num";
> if ( ( $num % 2 ) == 0 ) { $num /= 2 } # if even, divide by 2
> else { $num * 3; $num++; } #multiply by 3, then increment
I think this should be
else { $num *= 3; $num++; } #multiply by 3, then increment
^
$num * 3 doesn't change $num. *= would actually reassign.
The result of $num * 3 isn't going anywhere, so it's a void context.
$num *= 3 goes into $num, so the context isn't void -- scalar, I'd say.
Try it now.
> }
> print $num, "\n"; # I tried with and without the \n and the output
> never
> rendered differently?
> #push (my @numbers, $num); print '@numbers';
>
> Error: Useless use of multiplication in void context at
> C:\WINNT\Profiles\moi\Desktop\perl\lesson4\mea
> nder.pl line 9.
> Please type an integer:
>
> Please type an integer: 35
> 353618910563421
>
> The example is simply there to teach a looping construct, (it could
> be just a bad example..I doublechecked my typing, but my error is
> invisible to me at this point....)
I definitely don't like the formatting, but that's just me. Perl
doesn't care. =o)
> ?'s:
> What's void context?. I've seen it referenced using perldoc -q void,
> but don't quite follow the answers in perldoc?
Context is everything in perl. =o)
As I said above, the result was going nowhere, so what was the point?
The optimizer likely just removed the statement entirely from the
compilation cycle.
if you want to see context in action, run this:
================
my $f = <DATA>;
print $f;
__DATA__
a
b
c
d
================
Then change $f to @f, and run it again.
Reading into a scalar gives a scalar context, so <DATA> only returns
one line. Reading into @f is a list context, so <DATA> dumps the whole
file, one line per cell of the array.
even better, try this:
my $f = "abc" =~ /(.)/;
print "$f\n";
It prints 1. but this:
my($f) = "abc" =~ /(.)/;
print "$f\n";
prints "a". What's the difference? The parens around $f make it a list
context, so the match operator returns the list of things it matched
(though we only kept the first one). In a scalar context, it returns a
boolean 1 or '' that says whether it matched anything.
*READ* carefully about contexts in Perl. When using a new function, try
perldoc -f whatever
and pay close attention to what it does under different contexts.
Paul
__________________________________________________
Do You Yahoo!?
Yahoo! Auctions - buy the things you want at great prices
http://auctions.yahoo.com/