String Manipulation

I'm making a little game in Perl, and I am trying to remove the first instance of a character in an arbitrary string. For example, if the string is

"cupcakes"

and the user enters another string that contains letters from "cupcake" e.g:

"sake"

the original string will now look like this (below) because the "akes" has been taken away:

"cupc"

The user could also enter "cup" and then the string will look like "cakes".

At the moment I am iterating over the word the user has entered and getting the index of that letter within the original string. I can get this index just fine, but I am stuck at then removing that character (so that the char can't be used more than the number of times it appears in the original string).

Another example is the user enters "success" this should not be valid as the original string only has one "s".

Any help gratefully received.

Take the input (let's say $input) and remove the letters it contains from the variable containing the word (i.e. $word = "cupcakes"):

$word =~ s/$input//g;
1 Like

Perfecto.

I love this forum. :b:

Something like this (with lots of assumptions):

$input=shift @ARGV;
$str="cupcakes";
$input{$_}+=1 for split //,$input;
$str{$_}+=1 for split //,$str;
$substitute=1;
for (keys %input) {if ($input{$_} > $str{$_}) {$substitute=0;last}}
$str =~ s/[$input]//g if ($substitute and !($str =~ s/$input//));
print "$str\n"

Some trial runs:

perl <scriptname> sake
cupc

perl <scriptname> cup
cakes

perl <scriptname> success
cupcakes