Need to put a char in a str

Tags: perl random
Question!

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?=\



Answers

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}
By : Borodin


This video can help you solving your question :)
By: admin