Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: get it into one line ?

by athomason (Curate)
on Apr 16, 2001 at 13:49 UTC ( #72792=note: print w/ replies, xml ) Need Help??


in reply to get it into one line ?

> Ok this code should delete all multiple chars in $secret.

This spec is a bit uncertain: do you want to eliminated sequentially repeated characters ('bookkeeper' -> 'bokeper') or keep only one instance of each character ('bookkeeper' -> 'bokepr')? Gathering from your first attempt, you want the second behavior.

As an exercise, I'll demonstrate both, since they're both easy with regular expressions. Though your hash approach makes sense and is likely more efficient, I like the elegance of regexen. As always, TMTOWTDI.

The first case is quite simple; just use:($newsecret = $secret) =~ tr/a-zA-Z//s;
The /s flag instructs the transliteration operator to squash any repeated characters that are replaced. The empty replacement list causes the search list to be copied into the replacement list. So, the operator matches any character, replaces it with itself, and eliminates any sequential duplicates it comes along.

The second form takes a little bit more ninja magic, but I hope it's still understandable. After all, you're looking for concise, not pretty: for ( $newsecret = $secret; $newsecret =~ s/(([a-zA-Z]).*)\2/$1/; ){1};

You can't just use /g because the replacements should happen right to left. This is an ugly form of the 1 while (...) construct that sneaks the initial assignment into the line. If you don't mind modifying $secret in-place, you should use the cleaner form:1 while $secret =~ s/(([a-zA-Z]).*)\2/$1/;

The regexp finds any character followed by the same character later in the string and crops the latter. This is repeated until it no longer matches.

An important point is that I've assumed $secret contains only alphabetic characters. You'll need to change the matching character class according to the actual contents of your variable.

Though I doubt it applies to your case, if the final order of the string doesn't matter then you could use the hash method:

$newsecret = join '', keys %{{map {($_, 1)} split //, $secret}};


Comment on Re: get it into one line ?
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (14)
As of 2014-12-19 14:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (84 votes), past polls