Pathologically Eclectic Rubbish Lister PerlMonks

### Re: How to use regular expression for this?

by AReed (Pilgrim)
 on Aug 12, 2005 at 22:19 UTC ( #483438=note: print w/replies, xml ) Need Help??

in reply to How to use regular expression for this?

Must you use a regular expression? If not, this works:
```#!/usr/bin/perl
use warnings;
use strict;

my @teststrings = qw(ABCXXXXXX AXCXXXXXX AXXDXFXXX AXXXXXXHI XXXXXXGHI
+ XXXXXXXXX AXXXXXXXI);

my \$pattern = "ABCDEFGHI";
my \$desired_matches = 3;

for (@teststrings) {
my \$result = \$pattern ^ \$_;
my \$matches = \$result =~ tr/\0/ /;
print "\$_\n" if \$matches == \$desired_matches;
}

Replies are listed 'Best First'.
Re^2: How to use regular expression for this?
by Anonymous Monk on Aug 12, 2005 at 22:48 UTC
I don't have to use regular expression. Can you explain the meaning of: my \$result = \$pattern ^ \$_; my \$matches = \$result =~ tr/\0/ /; Thanks!!
To elaborate on QM's solution explanation of AReed's solution, the "^" (exclusive-OR) operator, applied to two strings, will treat them as bit vectors, and return a string whose characters each represent 8 bits, in proper order, from the XOR result.

If the two strings have the same character at the same offset, the XOR result will be zero (null byte); the "tr/\0/ /" operation will not only convert the nulls to spaces, but will also return the number of nulls found and converted.

It's okay if the two strings are not the same length, because the shorter one will be padded with nulls as needed (and any value XOR 0 gives back that same value).

```my \$result = \$pattern ^ \$_;
This XORs \$pattern and \$_ together, and stores it in \$result.
```my \$matches = \$result =~ tr/\0//;
This counts the number of matches, and puts that into \$matches.

-QM
--
Quantum Mechanics: The dreams stuff is made of

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://483438]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2023-02-07 17:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?