Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

logical Exclusive Or, xor

by fruiture (Curate)
on Oct 14, 2002 at 08:35 UTC ( #205048=perlmeditation: print w/replies, xml ) Need Help??

I have written a lot of code, probably not even a fraction of what experienced programmers have written, but quite a lot for my age i'd say (for I'm student and yet looking forward to studying CS and stuff).

Second, I really like playing around with the logical operators and short-circuit. That sometimes ends up in long but single statements.

my ($id,$pass,$user,$cookie); ( ( $id = $cgi->param( config('username_param') ) ) and ( $pass = $cgi->param( config('userpass_param') ) and $pass = crypt( $pass, $id ) ) ) or ( $cookie = do { require CGI::Cookie; my %c = CGI::Cookie->fetch; $c{ config('user_cookie') } } and ($id,$pass) = $cookie->value() ) or ($id,$pass) = (config('anonymous_name'),config('anonymous_pass'));

As you can guess and see from the example, the code i write is primarily for CGI stuff or short system-administration programs, rather pragmatic and often used only once. But the range of tasks is fairly broad.

But to the point: I have encountered many situations where "logical operator fun" can be used, but i have never used (it was never possible) the logical eclusive or.

Searching on this site gives me nodes that deal with XOR encryption, none deales with the 'xor' Operator.

Now, what i'd be interested in is: In what situations does the 'xor' come into play? I could imagine that scientific algorithms need it, but have you ever needed it in application code? My assumption that it seems to be "unused apart from demonstration of its functionailty" is strengthened by the fact that there seems to be only the bitwise XOR in C, no logical.

I'd really like to see snippets or explanations where the real-life use of Locigal Exclusive Or can be found or if it is just there for completeness.


Replies are listed 'Best First'.
Re: logical Exclusive Or, xor
by demerphq (Chancellor) on Oct 14, 2002 at 11:11 UTC
    I think that xor in a non binary sense is just there for completeness. I cant think of any times ive seen it in use in programming, but having said that I can think of a few places I might've used it had I realised it was there. (thanks, I knew it was there for bitwise use, but wasnt aware it was also available for logical use.)

    Where is binary XOR used? Well, binary adders are usually made up of a bunch of XOR's. (Or used to be anyway... :-)

    Also, it wouldnt suprise me if you went through your code that you might find a few implict xors. As xors can be constructed out of the other gates you may have used one inadverdantly without realizing.

    my @a=(0,0,1,1); my @b=(0,1,0,1); print " | _ +__________ \n"; print " | _ _ ___ ___ ___ ___ + ___ \n"; print " A B | A B (A&B) (A|B) (AxB) (A&B) (A|B) (AxB) ((A|B)&(A&B)) (( +A&B)|(A|B))\n"; print "-----+--------------------------------------------------------- +-----------\n"; for (0..3) { printf" %d %d | %d %d %d %d %d %d %d %d +%d %d \n", $a[$_], $b[$_], ($a[$_]?0:1), ($b[$_]?0:1), ($a[$_] and $b[$_]), ($a[$_] or $b[$_]), ($a[$_] xor $b[$_]), (($a[$_] and $b[$_])?0:1), (($a[$_] or $b[$_])?0:1), (($a[$_] xor $b[$_])?0:1), ((($a[$_] or $b[$_]) and ($a[$_] and $b[$_])?0:1)), ((($a[$_] and $b[$_]) or ($a[$_] or $b[$_])?0:1)?0:1); } __END__ | ________ +___ | _ _ ___ ___ ___ ___ _ +__ A B | A B (A&B) (A|B) (AxB) (A&B) (A|B) (AxB) ((A|B)&(A&B)) ((A&B)|(A +|B)) -----+---------------------------------------------------------------- +---- 0 0 | 1 1 0 0 0 1 1 1 0 0 0 1 | 1 0 0 1 1 1 0 0 1 1 1 0 | 0 1 0 1 1 1 0 0 1 1 1 1 | 0 0 1 1 0 0 0 1 0 0
    So any time you have written ($x || $y && !($x && $y)) you could have used $x xor $y.

    Incidentally, a little piece of trivia, xor is not only interesting due to its arithmetical properties, but also for the following fact: xor/xnor are the only (named)(useful) binary gates that _cannot_ be used to construct the rest. There are the unnamed gates (output 0101 and its complement 1010, and output 1100 and complement 0011) that share this fault, but afaik they arent used at all (and actually they simplify down to not(A) and not(B) and so theres no suprise there.) All of the rest when combined with not can be used to construct the rest, with NOR and NAND being particularly useful as they have no need for the supporting not gates. ( A NOR A=NOT A, A NAND A = NOT A )

    Hope this wasnt too OT for you, I always found logic gates to be fascinating things, (until I did a symbolic logic class and saw the horrible things that philosophers like to do with them... And never an XOR gate to be seen.... Upside down truth tables, funny symbols, grumble grumble grumble)


    --- demerphq
    my friends call me, usually because I'm late....

Re: logical Exclusive Or, xor
by Aristotle (Chancellor) on Oct 14, 2002 at 09:51 UTC

    The results of an XOR always depend on both operands, so it always evaluates both and thus is useless as far as control flow is concerned. Using XOR is the same as just writing the operands separately if you're not interested in the result.

    That code looks more like LISP than Perl if I may comment btw, and the first thing I'd do if I ran across it is rewrite. Use naked blocks, next and last in Perl, that's easier to read and just as efficient.

    Makeshifts last the longest.

      I don't follow why xor is useless, and and isn't. Afterall, if I'm not interested in the result, I can write
      EXPR1 and EXPR2;
      if (EXPR1) {EXPR2}

      And something similar for or.

      I've used xor, although not very often. A few months ago I used it in a program that took command line arguments. 2 options where multiple exclusive, but at least one of them had to be used. So I had something like:

      unless (defined ($opt1) xor defined ($opt2)) { die "usage message"; }

      I don't use xor often, but I still use it more than ;-).


        Afterall, if I'm not interested in the result, I can write EXPR1 and EXPR2; as if (EXPR1) {EXPR2}
        The former is what fruiture was doing. He was talking about shortcircuiting effects, after all. xor doesn't posess any.

        Makeshifts last the longest.

Re: logical Exclusive Or, xor
by John M. Dlugosz (Monsignor) on Oct 14, 2002 at 16:15 UTC
    Nobody on the thread has pointed out yet that a logical XOR is the same operation as != between booleans. So, people might use it more than they realize!

Re: logical Exclusive Or, xor
by tommyw (Hermit) on Oct 14, 2002 at 09:45 UTC

    I've got some code I'm working with at the moment, that validates sections of XML, according to a DTD-like regex.

    Sometimes the regex specifies bits I do want included (eg, dtd => '(open? #PCDATA? la #PCDATA? close?)+' collects our labels, and some attached text, delimeted by brackets.

    Sometimes, however, it's easier to say that I want everything except certain pieces swept together: dtd => '(p | n | nqp)+', rev => 1 excludes paragraphs and notes from being included in new paragraphs.

    The code I'm using to validate this is:

    my @kids=$_->children; my $struct=' '.join (' ', map { $_->tag} @kids).' '; my $hit=$struct=~/^(?:$subelms{$tag}{'dtd_re'})$/; $loose=!$hit; $loose=!$loose if $subelms{$tag}{'rev'};
    That is: build the string that represents the subelements, compare that to the specified dtd, and reverse the sense of the match if the rev attribute is set.

    The last couple of lines could be recoded as $loose=!$hit xor $subelms{$tag}{'rev'} (and probably will be now you've reminded me of this.

    Why don't I use xor more often? Well, if I'm dealing with only boolean values (0 and 1), then usually I find it clearer to use == or !=. If I'm not dealing with booleans, then I really don't want to touch xor.

    Too stupid to live.
    Too stubborn to die.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://205048]
Approved by vagnerr
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2019-06-18 22:40 GMT
Find Nodes?
    Voting Booth?
    Is there a future for codeless software?

    Results (83 votes). Check out past polls.

    • (Sep 10, 2018 at 18:53 UTC) Welcome new users!