Cari di Perl 
    Perl User Manual
Daftar Isi
(Sebelumnya) Right-to-left substring searchGet or alter a portion of a stirng (Berikutnya)
Functions for SCALARs or strings

Formatted print into a string

Daftar Isi

  • sprintf FORMAT, LIST

    Returns a string formatted by the usual printf conventions of the Clibrary function sprintf. See below for more detailsand see sprintf(3) or printf(3) on your system for an explanation ofthe general principles.

    For example:

    1. # Format number with up to 8 leading zeroes
    2. $result = sprintf("%08d", $number);
    3. # Round number to 3 digits after decimal point
    4. $rounded = sprintf("%.3f", $number);

    Perl does its own sprintf formatting: it emulates the Cfunction sprintf(3), but doesn't use it except for floating-pointnumbers, and even then only standard modifiers are allowed. Non-standard extensions in your local sprintf(3) are therefore unavailable from Perl.

    Unlike printf, sprintf does not do what you probably mean when youpass it an array as your first argument. The array is given scalar context,and instead of using the 0th element of the array as the format, Perl willuse the count of elements in the array as the format, which is almost neveruseful.

    Perl's sprintf permits the following universally-known conversions:

    1. %% a percent sign
    2. %c a character with the given number
    3. %s a string
    4. %d a signed integer, in decimal
    5. %u an unsigned integer, in decimal
    6. %o an unsigned integer, in octal
    7. %x an unsigned integer, in hexadecimal
    8. %e a floating-point number, in scientific notation
    9. %f a floating-point number, in fixed decimal notation
    10. %g a floating-point number, in %e or %f notation

    In addition, Perl permits the following widely-supported conversions:

    1. %X like %x, but using upper-case letters
    2. %E like %e, but using an upper-case "E"
    3. %G like %g, but with an upper-case "E" (if applicable)
    4. %b an unsigned integer, in binary
    5. %B like %b, but using an upper-case "B" with the # flag
    6. %p a pointer (outputs the Perl value's address in hexadecimal)
    7. %n special: *stores* the number of characters output so far
    8. into the next argument in the parameter list

    Finally, for backward (and we do mean "backward") compatibility, Perlpermits these unnecessary but widely-supported conversions:

    1. %i a synonym for %d
    2. %D a synonym for %ld
    3. %U a synonym for %lu
    4. %O a synonym for %lo
    5. %F a synonym for %f

    Note that the number of exponent digits in the scientific notation producedby %e, %E, %g and %G for numbers with the modulus of theexponent less than 100 is system-dependent: it may be three or less(zero-padded as necessary). In other words, 1.23 times ten to the99th may be either "1.23e99" or "1.23e099".

    Between the % and the format letter, you may specify severaladditional attributes controlling the interpretation of the format.In order, these are:

    • format parameter index

      An explicit format parameter index, such as 2$. By default sprintfwill format the next unused argument in the list, but this allows youto take the arguments out of order:

      1. printf '%2$d %1$d', 12, 34; # prints "34 12"
      2. printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1"
    • flags

      one or more of:

      1. space prefix non-negative number with a space
      2. + prefix non-negative number with a plus sign
      3. - left-justify within the field
      4. 0 use zeros, not spaces, to right-justify
      5. # ensure the leading "0" for any octal,
      6. prefix non-zero hexadecimal with "0x" or "0X",
      7. prefix non-zero binary with "0b" or "0B"

      For example:

      1. printf '<% d>', 12; # prints "< 12>"
      2. printf '<%+d>', 12; # prints "<+12>"
      3. printf '<%6s>', 12; # prints "< 12>"
      4. printf '<%-6s>', 12; # prints "<12 >"
      5. printf '<%06s>', 12; # prints "<000012>"
      6. printf '<%#o>', 12; # prints "<014>"
      7. printf '<%#x>', 12; # prints "<0xc>"
      8. printf '<%#X>', 12; # prints "<0XC>"
      9. printf '<%#b>', 12; # prints "<0b1100>"
      10. printf '<%#B>', 12; # prints "<0B1100>"

      When a space and a plus sign are given as the flags at once,a plus sign is used to prefix a positive number.

      1. printf '<%+ d>', 12; # prints "<+12>"
      2. printf '<% +d>', 12; # prints "<+12>"

      When the # flag and a precision are given in the %o conversion,the precision is incremented if it's necessary for the leading "0".

      1. printf '<%#.5o>', 012; # prints "<00012>"
      2. printf '<%#.5o>', 012345; # prints "<012345>"
      3. printf '<%#.0o>', 0; # prints "<0>"
    • vector flag

      This flag tells Perl to interpret the supplied string as a vector ofintegers, one for each character in the string. Perl applies the format toeach integer in turn, then joins the resulting strings with a separator (adot . by default). This can be useful for displaying ordinal values ofcharacters in arbitrary strings:

      1. printf "%vd", "AB\x{100}"; # prints "65.66.256"
      2. printf "version is v%vd\n", $^V; # Perl's version

      Put an asterisk * before the v to override the string touse to separate the numbers:

      1. printf "address is %*vX\n", ":", $addr; # IPv6 address
      2. printf "bits are %0*v8b\n", " ", $bits; # random bitstring

      You can also explicitly specify the argument number to use forthe join string using something like *2$v; for example:

      1. printf '%*4$vX %*4$vX %*4$vX', @addr[1..3], ":"; # 3 IPv6 addresses
    • (minimum) width

      Arguments are usually formatted to be only as wide as required todisplay the given value. You can override the width by puttinga number here, or get the width from the next argument (with *)or from a specified argument (e.g., with *2$):

      1. printf "<%s>", "a"; # prints "<a>"
      2. printf "<%6s>", "a"; # prints "< a>"
      3. printf "<%*s>", 6, "a"; # prints "< a>"
      4. printf "<%*2$s>", "a", 6; # prints "< a>"
      5. printf "<%2s>", "long"; # prints "<long>" (does not truncate)

      If a field width obtained through * is negative, it has the sameeffect as the - flag: left-justification.

    • precision, or maximum width

      You can specify a precision (for numeric conversions) or a maximumwidth (for string conversions) by specifying a . followed by a number.For floating-point formats except g and G, this specifieshow many places right of the decimal point to show (the default being 6).For example:

      1. # these examples are subject to system-specific variation
      2. printf '<%f>', 1; # prints "<1.000000>"
      3. printf '<%.1f>', 1; # prints "<1.0>"
      4. printf '<%.0f>', 1; # prints "<1>"
      5. printf '<%e>', 10; # prints "<1.000000e+01>"
      6. printf '<%.1e>', 10; # prints "<1.0e+01>"

      For "g" and "G", this specifies the maximum number of digits to show,including those prior to the decimal point and those after it; for example:

      1. # These examples are subject to system-specific variation.
      2. printf '<%g>', 1; # prints "<1>"
      3. printf '<%.10g>', 1; # prints "<1>"
      4. printf '<%g>', 100; # prints "<100>"
      5. printf '<%.1g>', 100; # prints "<1e+02>"
      6. printf '<%.2g>', 100.01; # prints "<1e+02>"
      7. printf '<%.5g>', 100.01; # prints "<100.01>"
      8. printf '<%.4g>', 100.01; # prints "<100>"

      For integer conversions, specifying a precision implies that theoutput of the number itself should be zero-padded to this width,where the 0 flag is ignored:

      1. printf '<%.6d>', 1; # prints "<000001>"
      2. printf '<%+.6d>', 1; # prints "<+000001>"
      3. printf '<%-10.6d>', 1; # prints "<000001 >"
      4. printf '<%10.6d>', 1; # prints "< 000001>"
      5. printf '<%010.6d>', 1; # prints "< 000001>"
      6. printf '<%+10.6d>', 1; # prints "< +000001>"
      7. printf '<%.6x>', 1; # prints "<000001>"
      8. printf '<%#.6x>', 1; # prints "<0x000001>"
      9. printf '<%-10.6x>', 1; # prints "<000001 >"
      10. printf '<%10.6x>', 1; # prints "< 000001>"
      11. printf '<%010.6x>', 1; # prints "< 000001>"
      12. printf '<%#10.6x>', 1; # prints "< 0x000001>"

      For string conversions, specifying a precision truncates the stringto fit the specified width:

      1. printf '<%.5s>', "truncated"; # prints "<trunc>"
      2. printf '<%10.5s>', "truncated"; # prints "< trunc>"

      You can also get the precision from the next argument using .*:

      1. printf '<%.6x>', 1; # prints "<000001>"
      2. printf '<%.*x>', 6, 1; # prints "<000001>"

      If a precision obtained through * is negative, it countsas having no precision at all.

      1. printf '<%.*s>', 7, "string"; # prints "<string>"
      2. printf '<%.*s>', 3, "string"; # prints "<str>"
      3. printf '<%.*s>', 0, "string"; # prints "<>"
      4. printf '<%.*s>', -1, "string"; # prints "<string>"
      5. printf '<%.*d>', 1, 0; # prints "<0>"
      6. printf '<%.*d>', 0, 0; # prints "<>"
      7. printf '<%.*d>', -1, 0; # prints "<0>"

      You cannot currently get the precision from a specified number,but it is intended that this will be possible in the future, forexample using .*2$:

      1. printf "<%.*2$x>", 1, 6; # INVALID, but in future will print "<000001>"
    • size

      For numeric conversions, you can specify the size to interpret thenumber as using l, h, V, q, L, or ll. For integerconversions (d u o x X b i D U O), numbers are usually assumed to bewhatever the default integer size is on your platform (usually 32 or 64bits), but you can override this to use instead one of the standard C types,as supported by the compiler used to build Perl:

      1. hh interpret integer as C type "char" or "unsigned char"
      2. on Perl 5.14 or later
      3. h interpret integer as C type "short" or "unsigned short"
      4. j interpret integer as C type "intmax_t" on Perl 5.14
      5. or later, and only with a C99 compiler (unportable)
      6. l interpret integer as C type "long" or "unsigned long"
      7. q, L, or ll interpret integer as C type "long long", "unsigned long long",
      8. or "quad" (typically 64-bit integers)
      9. t interpret integer as C type "ptrdiff_t" on Perl 5.14 or later
      10. z interpret integer as C type "size_t" on Perl 5.14 or later

      As of 5.14, none of these raises an exception if they are not supported onyour platform. However, if warnings are enabled, a warning of theprintf warning class is issued on an unsupported conversion flag. Should you instead prefer an exception, do this:

      1. use warnings FATAL => "printf";

      If you would like to know about a version dependency before youstart running the program, put something like this at its top:

      1. use 5.014; # for hh/j/t/z/ printf modifiers

      You can find out whether your Perl supports quads via Config:

      1. use Config;
      2. if ($Config{use64bitint} eq "define" || $Config{longsize} >= 8) {
      3. print "Nice quads!\n";
      4. }

      For floating-point conversions (e f g E F G), numbers are usually assumedto be the default floating-point size on your platform (double or long double),but you can force "long double" with q, L, or ll if yourplatform supports them. You can find out whether your Perl supports longdoubles via Config:

      1. use Config;
      2. print "long doubles\n" if $Config{d_longdbl} eq "define";

      You can find out whether Perl considers "long double" to be the defaultfloating-point size to use on your platform via Config:

      1. use Config;
      2. if ($Config{uselongdouble} eq "define") {
      3. print "long doubles by default\n";
      4. }

      It can also be that long doubles and doubles are the same thing:

      1. use Config;
      2. ($Config{doublesize} == $Config{longdblsize}) &&
      3. print "doubles are long doubles\n";

      The size specifier V has no effect for Perl code, but is supported forcompatibility with XS code. It means "use the standard size for a Perlinteger or floating-point number", which is the default.

    • order of arguments

      Normally, sprintf() takes the next unused argument as the value toformat for each format specification. If the format specificationuses * to require additional arguments, these are consumed fromthe argument list in the order they appear in the formatspecification before the value to format. Where an argument isspecified by an explicit index, this does not affect the normalorder for the arguments, even when the explicitly specified indexwould have been the next argument.

      So:

      1. printf "<%*.*s>", $a, $b, $c;

      uses $a for the width, $b for the precision, and $cas the value to format; while:

      1. printf "<%*1$.*s>", $a, $b;

      would use $a for the width and precision, and $b as thevalue to format.

      Here are some more examples; be aware that when using an explicitindex, the $ may need escaping:

      1. printf "%2\$d %d\n", 12, 34; # will print "34 12\n"
      2. printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n"
      3. printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n"
      4. printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n"

    If use locale (including use locale 'not_characters') is in effectand POSIX::setlocale() has been called,the character used for the decimal separator in formatted floating-pointnumbers is affected by the LC_NUMERIC locale. See perllocaleand POSIX.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Right-to-left substring searchGet or alter a portion of a stirng (Berikutnya)