Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Making a variable tab string

by sandrider (Acolyte)
on Feb 21, 2007 at 05:19 UTC ( #601268=perlquestion: print w/replies, xml ) Need Help??

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 (Monsignor) 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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://601268]
Approved by stonecolddevin
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2021-06-13 09:30 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (54 votes). Check out past polls.