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

I am writing out a textfile that has spaces throughout the file. What I need to do is put spaces in locations that may not have a value to put in. For example: $Reserve_1 requires 11 spaces in the field so my code looks like this..
sub checkData { my $zero = 0; my $space = ' '; if($Coverage_limits.length lt 11) { $Coverage_limits = ' '; } if($Reserve_1) { $Reserve_1 = ' '; } if($Coverage_entry_date != "") { my $year = substr(@row[3], 2, 2); my $month = $zero.@row[4]; my $day = $zero.@row[5]; $Coverage_entry_date = $year.$month.$day; } }
This does not work. Thanks for your help in advance.

Replies are listed 'Best First'.
Re: I need a regExp to add spaces
by trammell (Priest) on Mar 17, 2005 at 21:46 UTC
    if($Coverage_entry_date != "")
    The ne operator determines string inequality in Perl:
    if($Coverage_entry_date ne "")
    see perlop for details.
Re: I need a regExp to add spaces
by beauregard (Monk) on Mar 17, 2005 at 23:38 UTC
    Sounds like a job for sprintf.
    $Coverage_limits = sprintf("%-11.11s", $Coverage_limits);
    c.
      c,
      $LimitValue = sprintf("%-1.1s", $LimitValue);
      Is it possible in the above line of code to make the 1's into variables? eg.
      $LimitValue = sprintf("%-$length.$lengths", $LimitValue);
      Thanks in advance
        Of course. The obvious way:
        my $vlen = 1; $LimitValue = sprintf("%-${vlen}.${vlen}s", $LimitValue);

        The "real" sprintf to do variable field sizes is:

        $LimitValue = sprintf("%-*s", $vlen, $LimitValue);

        You can also do:

        $formatter = sprintf( "%%-%d.%ds", $vlen, $vlen ); $LimitValue = sprintf($formatter, $LimitValue);
        if you wanted to reuse the formatter elsewhere.

        c.

Re: I need a regExp to add spaces
by naChoZ (Curate) on Mar 17, 2005 at 21:57 UTC

    You could probably handle this during output with write.

    format FOO = @<<<<<<<<<<< $Reserve_1 . ..in a nearby piece of code.. open(FOO, ">myfile"); select(FOO); write;

    You aren't limited to filehandles, you can even use STDOUT.

    --
    "This alcoholism thing, I think it's just clever propaganda produced by people who want you to buy more bottled water." -- pedestrianwolf

Re: I need a regExp to add spaces
by sh1tn (Priest) on Mar 17, 2005 at 21:53 UTC
    # or ... if($Coverage_limits.length !~ /^\s{11}$/o) ...


Re: I need a regExp to add spaces
by eieio (Pilgrim) on Mar 17, 2005 at 21:53 UTC
    While I don't completely understand your question, I'll take a guess that perlform may help.
Re: I need a regExp to add spaces
by eXile (Priest) on Mar 18, 2005 at 14:53 UTC
    I'm not too sure the construct $Coverage_limits.length does what you want it to do, it will concatenate $Coverage_limits with the length of $_.

    I suppose you mean length($Coverage_limits)?