Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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}};

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://72792]
[ambrus]: YourMother: my brother told me their cat wants to climb into the dishwasher if they leave the door open. Not when the dishwasher is started, but after it's done washing, because it's still warm and cats like warm.
[Your Mother]: Sure, sure. I had a cat as a kid who always slept on top of the fridge because of the heat dissipation up the back.

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (14)
As of 2017-12-18 15:32 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (492 votes). Check out past polls.