snape has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I think my question may be stupid but I don't know why I am not able to do it. I am trying to add tab spaces between each characters by using substitute command and it doesn't seem to work properly.

Code Snippet:

#!/usr/bin/perl use strict; use warnings; my $bar1 = 'this002haa007hoothat'; my $bar2 = 'abcdef'; my $bar3 = $bar1.$bar2; $bar3 =~ s/\t$//g; print $barb, "\n";

Can you explain where I am doing a blunder ?

Replies are listed 'Best First'.
Re: Substitute: for having tabs between the characters
by almut (Canon) on Apr 13, 2010 at 05:42 UTC

    Try

    $bar3 =~ s/(.)(?!\z)/$1\t/g;

    i.e. for every character except the last one (-> (?!\z)), replace it with itself plus a tab.

    (What your substitution would do is remove a trailing tab.)

      Thanks a lot.

Re: Substitute: for having tabs between the characters
by CountZero (Bishop) on Apr 13, 2010 at 06:05 UTC
    Or using join, split and the null pattern:
    $bar3 = join "\t", split //, $bar3;

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Substitute: for having tabs between the characters
by Marshall (Canon) on Apr 13, 2010 at 07:35 UTC
    I am engaging in some "mind reading" here. Maybe you just want a tab between $bar1 and $bar2? A tab character between each individual character of a long string would be a rather strange application - more likely is a tab between "word" tokens. A short example of the desired output would have made things crystal clear.
    #!/usr/bin/perl use strict; use warnings; my $bar1 = 'this002haa007hoothat'; my $bar2 = 'abcdef'; my $bar3 = "$bar1\t$bar2"; print "$bar3\n"; #or without $bar3 print "$bar1\t$bar2\n"; __END__ prints: this002haa007hoothat abcdef this002haa007hoothat abcdef

      I am sorry to say that your mind reading was not correct. I was actually looking for the fault in my substitute command but thanks for your intuitive thinking . :)

        Thanks for your reply! Hey, no problem. Sometimes its hard to figure out what is going on. :-) Was just trying to be helpful.