Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: string comparison

by BrowserUk (Patriarch)
on May 27, 2005 at 07:23 UTC ( #460969=note: print w/replies, xml ) Need Help??

in reply to string comparison

You could just rejoin your strings after spliting and sorting and then compare them:

#! perl -slw use strict; sub reorder { my $string = shift; return join ',', sort{ $a cmp $b } split ',', $string; };; my $string1 = '~cake,pastry'; my $string2 = 'pastry,~cake'; my $string3 = 'cake,pastry'; print "$_->[ 0 ] eq $_->[ 1 ]", reorder( $_->[ 0 ] ) eq reorder( $_->[ 1 ] ) ? ' match ' : ' dont match' for [ $string1, $string2 ], [ $string1, $string3 ], [ $string2, $string3 ]; __END__ [ 8:16:14.39] P:\test>junk2 ~cake,pastry eq pastry,~cake match ~cake,pastry eq cake,pastry dont match pastry,~cake eq cake,pastry dont match

Not hugely efficient, but probably not too bad if there are only a few elements in your strings.

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.

Replies are listed 'Best First'.
Re^2: string comparison
by reasonablekeith (Deacon) on May 27, 2005 at 08:51 UTC
    Seems like an overly complicated example. Isn't it just as simple as... ?
    my $string1 = '~cake,pastry'; my $string2 = 'pastry,~caske'; if (sort_text($string1) eq sort_text($string2)) { print "match\n"; } sub sort_text { join(',', sort split(/,/, $_[0]) ) }
    my name's not Keith, and I'm not reasonable.
      Extending this logic a bit, and using <DATA> to read in the test data:
      use strict; use warnings; my ($first_line, $current_line); while (<DATA>) { chomp; # get rid of newline # get the first line sorted if ($. == 1) { $first_line = join ",", sort( split /,/,); } else { #die if doesn't match the first line sorted. $current_line = join ",", sort( split /,/,); die "$_ didn't match first line" unless $current_line eq $firs +t_line; } } __DATA__ ~cake,pastry,donuts,meringue pastry,~cake,meringue,donuts meringue, donuts,pastry,~cake,meringue
      This dies on the third line, as it should.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://460969]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2023-02-06 12:16 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (34 votes). Check out past polls.