beginners:
Here's a second try at using bitwise xor-equals to implement boolean
pre- and post-invert operations for variables containing canonical
boolean values (undef, empty string, zero, and one).
The pre-invert semantics case (invert, then use) uses the bitwise
xor-equals operator and one, as before, but I found that parentheses are
sometimes required:
($v ^= 1)
The post-invert semantics case (use, then invert) can be obtained by
using the "scalar" operator on a parenthesized list:
scalar ($v ^= 1, !$v)
RTFM "perldoc -f scalar":
scalar EXPR
...
Because "scalar" is unary operator, if you accidentally use for
EXPR a parenthesized list, this behaves as a scalar comma
expression, evaluating all but the last element in void context
and returning the final element evaluated in scalar context.
This is seldom what you want.
The first list element inverts and saves the value of $v, the second
list element evaluates to the inverse of the inverse, which is the same
(in boolean context) as the original, and "scalar" returns that. This
is what we want.
HTH,
David
2013-09-10 16:31:14 dpchrist@desktop ~/sandbox/perl
$ cat xor-equal2.pl
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $v;
sub dump_v { Data::Dumper->Dump([$v], [qw(v)]) };
$v = undef;
print dump_v();
print 'pre-invert is ', ($v ^= 1) ? 'T' : 'F', "\n";
print dump_v();
print 'pre-invert is ', ($v ^= 1) ? 'T' : 'F', "\n";
print dump_v();
$v = undef;
print dump_v();
print 'post-invert is ', scalar ($v ^= 1, !$v) ? 'T' : 'F', "\n";
print dump_v();
print 'post-invert is ', scalar ($v ^= 1, !$v) ? 'T' : 'F', "\n";
print dump_v();
2013-09-10 16:31:17 dpchrist@desktop ~/sandbox/perl
$ perl xor-equal2.pl
$v = undef;
pre-invert is T
$v = 1;
pre-invert is F
$v = 0;
$v = undef;
post-invert is F
$v = 1;
post-invert is T
$v = 0;
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/