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

For instance, I can control the length for a string in the example below and get a print as "Vina"
my $string = "Vinay"; printf('%-4.4s', $string); print "\n";
The below set of statements prints 40000. How can I control the length of the float using printf to print 4000 even though the value of num is 40000?
my $num = 40000; printf('%4.0f', $num); print "\n";

Replies are listed 'Best First'.
Re: Length of float using printf
by bart (Canon) on Jun 02, 2009 at 18:35 UTC
    You seem to want the equivalent of BASIC's Left$. In Perl, we have substr, though we can also get by with pack/unpack, with template "A4", that behave differently on edge cases:
    $out = pack "A4", $string;
    will always produce a string of 4 characters, padded with spaces if shorter
    $out = unpack "A4", $string;
    will break off a string after 4 characters, and remove trailing spaces. (Bytes, actually...)
    $out = substr $string, 0, 4;
    The easiest approach, cutting off a substring of at most 4 characters (yes, characters).
      "A" works with characters since 5.10. (It still works with bytes, being a subset of characters.)
      >perl588\bin\perl -MTest::More=no_plan -e"$s=join '', map chr, 0x2660. +.0x2666; is(unpack('A4',$s), substr($s,0,4))" not ok 1 [...] 1..1 # Looks like you failed 1 test of 1. >perl589\bin\perl -MTest::More=no_plan -e"$s=join '', map chr, 0x2660. +.0x2666; is(unpack('A4',$s), substr($s,0,4))" not ok 1 [...] 1..1 # Looks like you failed 1 test of 1. >perl5100\bin\perl -MTest::More=no_plan -e"$s=join '', map chr, 0x2660 +..0x2666; is(unpack('A4',$s), substr($s,0,4))" ok 1 1..1
        So, I have decided to implement the substr and change the way my application uses it. Thanks again for all the inputs.
      I want to use printf only as my application uses printf and stores the format type in the object. The reason I want to represent 40000 as 4000 as it is incorrect if somebody is passing 40000. My object can't figure that out. It is for error handling.

        printf doesn't chop anything except the decimal portion. It makes sense since 40000 means something very different than 4000 (left-chopped) or 0000 (right-chopped), while 5.123 and 5.12 are similar.

        You can still use printf, but you first need to chop it using substr, unpack or some other means.