Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Nonrepeating characters in an RE

by atcroft (Abbot)
on Aug 16, 2022 at 03:36 UTC ( [id://11146153]=note: print w/replies, xml ) Need Help??


in reply to Nonrepeating characters in an RE

Interesting problem. Out of curiousity, I played around with the idea and got the following (ugly!) one-liner to work (reformatted for readability):

$ perl -le ' my @arry = qw/ a b cd gefge hhi jjkk l m nn o /; print q{Originals: }, join q{ }, @arry; my @n_arry = grep { if ( $_ !~ m/(.).*?\g-1/ ) { $_; } } @arry; print q{Uniques: }, join q{ }, @n_arry; ' Originals: a b cd gefeg hhi jjk l m nn o Uniques: a b cd l m o $

It can probably be cleaned up or made shorter (as I was just trying to get something working).

I originally approached the idea of doing a split-sort-join on the original string to get an ordered string, testing that for duplicate characters, but after getting it working I realized the grep() was the meat of the code, and the rest could be eliminated.

For anyone curious, here was my original code:

$ perl -le ' my @arry = qw/ a b cd gefge hhi jjkk l m nn o /; print q{Originals: }, join q{ }, @arry; my @n_arry = map { $_->{ori} } grep { if ( $_->{ordered} !~ m/(.).*?\g-1/gx ) { $_; } } map { my $str = my $o_str = $_; my @p = sort { $a cmp $b } split //, $o_str; $str = join q{ }, @p; { ori => $o_str, ordered => $str, }; } @arry; print q{Uniques: }, join q{ }, @n_arry; ' Originals: a b cd gefeg hhi jjk l m nn o Uniques: a b cd l m o $

Hope that helps.

Here's a shorter value for a single string:

$ perl -le ' my $str = shift; print q{Original: }, $str; print q{Unique: }, grep { if ( $_ !~ m/(.).*?\g-1/ ) { $_; }; } ( $str, ); ' foobar Original: foobar Unique: $ perl -le ' my $str = shift; print q{Original: }, $str; print q{Unique: }, grep { if ( $_ !~ m/(.).*?\g-1/ ) { $_; }; } ( $str, ); ' bar Original: bar Unique: bar

Update: (2022-08-15) - Removed unnecessary '/g' and '/x' from the regex in the grep. Removed an errant line of text that was left while editing the response. Removed READMORE tags around first code snippet. Fixed punctuation error in response text. Added shorter code examples at end.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2025-12-13 12:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (93 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.