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

Hi guys, I have this program that adds tabs to a string. I'm currently using this method to increase the number of tabs accordingly
for ($i = 0; $i < $numTabs; $i++) { $tabs = "tabs\t"; }
I believe that is a more elegant way of doing it. Can anyone enlighten me? Thanks. Desmond

Replies are listed 'Best First'.
Re: Making a variable tab string
by jwkrahn (Abbot) on Feb 21, 2007 at 05:27 UTC
    I suppose that you want something like:
    $tabs = 'tabs' . ( "\t" x $numTabs );
    ???
Re: Making a variable tab string
by GrandFather (Saint) on Feb 21, 2007 at 06:34 UTC

    You have the canonical answer from jwkrahn. However your code indicates a few opportunities for learning.

    First off always use strictures (use strict; use warnings;).

    Perl programers seldom use a C style for. The more usual way to iterate a fixed number of times is:

    for my $index (1 .. $numTabs) { ... }

    Although in the case in hand you don't need the counter at all. You could just:

    for (1 .. $numTabs) { ... }

    and if there is only one simple statement in the loop you can use the for as a modifier:

    ... for 1 .. $numTabs;

    I suspect there is a transcription error in your sample code. Most likely what you intended was:

    $tabs = "$tabs\t";

    in which case Perl allows you to use the concatenation assignment operator:

    $tabs .= "\t";

    so a more Perlish technique (without using the x operator) is

    $tabs .= "\t" for 1 .. $numTabs;

    DWIM is Perl's answer to Gödel
      Cool. Thanks a lot.
Re: Making a variable tab string
by bart (Canon) on Feb 21, 2007 at 12:43 UTC
    You seem to have mistyped "tabs\t" for "$tabs\t". In that case, you can use the more elegant operator .=:
    for ($i = 0; $i < $numTabs; $i++) { $tabs .= "\t"; }

    But, like jwkrahn wrote: you might as well use x instead of the loop, so this becomes:

    $tabs .= "\t" x $numTabs;
      Thank you.