in reply to Counting to add space to a string

Take choroba's length suggestion to heart; it's probably the best way to go...

But, for purposes of generalizing your modification procedure (which is both overkill and underkill, try this for size:

#!/usr/bin/perl use strict; use warnings; # 927370 - OP seeks to insert 'X' enough times to pad to len=14 AFTER +the LETTERS use 5.012; # NB: First account in this array needs more than one 'X'tension... my @account = qw/CAL2345-06 CALI123456-09 FLOR1234567-01/; for my $account(@account) { my $total_count = 0; while ($account =~ m/./g) { $total_count++ ; } say "At ln 15, |$account| has $total_count characters"; while ($total_count < 14) { substr($account, 4, 0) = 'X'; $total_count++; } continue { # loop till $total_count == 14 ! say "At ln 21, |$account| has $total_count characters"; } next; }

Execution and output:

C:\>927370.pl At ln 15, |CAL2345-06| has 10 characters At ln 21, |CAL2X345-06| has 11 characters <!-- first insert, X in wro +ng position At ln 21, |CAL2XX345-06| has 12 characters At ln 21, |CAL2XXX345-06| has 13 characters At ln 21, |CAL2XXXX345-06| has 14 characters <!-- but we do get to 14, + despite short orig. At ln 15, |CALI123456-09| has 13 characters At ln 21, |CALIX123456-09| has 14 characters <!-- 14 after extension At ln 15, |FLOR1234567-01| has 14 characters <!-- 14 in original array C:\>

hth

Extensively updated: pasted similar output and code but with mismatching ln numbers.

Replies are listed 'Best First'.
Re^2: Counting to add space to a string
by Util (Priest) on Sep 22, 2011 at 15:48 UTC

    In your first example, your code is inserting the X after the fourth char, but the OP says "after the initial letters".

      Good point; ++. Another arguement for regex and length!>

      I failed to consider that OP's substr($account_1, 4, 0) hard codes the insert point; in fact, offhand, I don't see a direct way (other than a regex to find the last, initial letter (.oO ... there might be some non-initial letters? pos, and length) to fix that in my code.

      Update: That is, I didn't see it until your Re: Counting to add space to a string. Elegant and concise: ++ again!