in reply to Alternative to substr on unknown length of scalar

sprintf("%.6s", $line)

update I misunderstood the question. I thought you wanted at most 6 characters, but it seems you want always exactly 6 characters. In that case use:

sprintf("%6.6s", $line)

Replies are listed 'Best First'.
Re^2: Alternative to substr on unknown length of scalar
by periapt (Hermit) on Oct 19, 2004 at 13:04 UTC
    This never works for me. In the event that len($line) > 6, sprintf will print the entire string as follows: (Win32/ActiveState 5.6.1)
    use strict; use warnings; use diagnostics; my $line = 'a'x 8; my $prnline = sprintf("len(line) > 6: [%-6s]\n",$line); $line = 'b' x 6; $prnline .= sprintf("len(line) = 6: [%-6s]\n",$line); $line = 'c' x 3; $prnline .=sprintf("len(line) n 6: [%-6s]\n",$line); print $prnline; __END__ len(line) > 6: [aaaaaaaa] len(line) = 6: [bbbbbb] len(line) n 6: [ccc ]

    I usually go with ikegami's option

    PJ
    use strict; use warnings; use diagnostics;
      It's a . (maximum length) before the 6, not a - (justify left)

      And it should work everywhere, otherwise you found a bug.

        Well, what do you know. Learn something new everyday here at the monestary. I've always overlooked the maximal modifier for strings. Thanks :o)

        PJ
        use strict; use warnings; use diagnostics;
Re^2: Alternative to substr on unknown length of scalar
by PerlingTheUK (Hermit) on Oct 19, 2004 at 11:02 UTC
    Ouch! how simple.

    Cheers,
    PerlingTheUK