user1779868
user1779868

Reputation: 101

Need to put a char in a str

I have a string $str = 'Hello my friends'; I need to put a char \ into every word and to get any posibble variety of this.

For example in stdout I want to get

{H\ello|He\llo|Hel\lo|Hell\o} {m\y} {f\riens|fr\iends|fri\ends.....}

I wrote some code, but I can't imagine what to do next:

my $str = 'Hello my friends';
my @ra = split / /, $str;
for(my $i=0; $i < scalar @ra; $i++)
{
    my $word = $ra[$i];
    my $num = length($word);
    my @chars = split("", $word);

    for(my $k = 0, my $l = 1; $l < $num; $k++,$l++)
    {
        print $chars[$k]."\\".$chars[$l];   
    }

}

Any ideas?=\

Upvotes: 1

Views: 91

Answers (2)

ikegami
ikegami

Reputation: 385829

my $str = 'Hello my friends';
$str =~ s{(\S{2,})}{
    my @alts;
    for my $i (1..length($1)-1) {
        my $slashed = $1;
        substr($slashed, $i, 0, '\\');
        push @alts, $slashed;
    }
    '{' . join('|', @alts) . '}'
}eg;

Upvotes: 2

Borodin
Borodin

Reputation: 126722

I suggest you use the facility of substr that allows you to supply a fourth parameter that supplies a new string that should take the place of the substring specified. So

my $string = 'ABCD';
substr $string, 2, 0, '\\';

will result in $string being equal to AB\CD.

This program provides a solution to your problem using this

use strict;
use warnings;

my $str = 'Hello my friends';

my @words = split ' ', $str;
my @new_words;

foreach my $word (@words) {
  my @list
  for my $i (1 .. length($word) - 1) {
    substr my $new_word = $word, $i, 0, '\\';
    push @list, $new_word;
  }
  push @new_words, join '|', @list;
}

my $new_str = join ' ', map "{$_}", @new_words;

print $new_str;

output

{H\ello|He\llo|Hel\lo|Hell\o} {m\y} {f\riends|fr\iends|fri\ends|frie\nds|frien\ds|friend\s}

Upvotes: 0

Related Questions