7
 1/ 15/2015 spri ntf - perl doc.perl .org ht tp: //perl doc.perl . org/functi ons/spri ntf. html 1/ 7 Perl Programming Documentation Download Perl Explore Perl version Select... Preferences Manual Overview Tutorials FAQs Histor y / Changes License Reference Language Functions Operators Special Variables Pragmas Utilities Internals Platform Specific Modules A  B C D E F  G H I L M  N O P S T U X sprintf Perl functions A-Z | Perl functions by category | The 'perlfunc' manpage sprintf FORMAT, LIST Returns a string formatted by the usual printf conventions of the C library function sprintf. See  below for more details and see  sprintf(3) or printf(3) on your system for an explanation of the general principles.

Sprintf - Perldoc.perl

Embed Size (px)

DESCRIPTION

Perl, sprintf,c++

Citation preview

  • 1/15/2015 sprintfperldoc.perl.org

    http://perldoc.perl.org/functions/sprintf.html 1/7

    PerlProgrammingDocumentationDownloadPerlExplore

    Perlversion

    Select...

    Preferences

    Manual

    OverviewTutorialsFAQsHistory/ChangesLicense

    Reference

    LanguageFunctionsOperatorsSpecialVariablesPragmasUtilitiesInternalsPlatformSpecific

    Modules

    ABCDEFGHILMNOPSTUX

    sprintfPerlfunctionsAZ|Perlfunctionsbycategory|The'perlfunc'manpage

    sprintfFORMAT,LIST

    ReturnsastringformattedbytheusualprintfconventionsoftheClibraryfunctionsprintf.Seebelowformoredetailsandseesprintf(3)orprintf(3)onyoursystemforanexplanationofthegeneralprinciples.

    http://www.perl.org/http://perldoc.perl.org/index-modules-C.htmlhttp://perldoc.perl.org/index-internals.htmlhttp://perldoc.perl.org/index-platforms.htmlhttp://perldoc.perl.org/index-tutorials.htmlhttp://perldoc.perl.org/index-modules-I.htmlhttp://perldoc.perl.org/index-functions.htmlhttp://www.perlfoundation.org/http://perldoc.perl.org/index-faq.htmlhttp://www.perlbuzz.com/http://perldoc.perl.org/index-modules-U.htmlhttp://www.pm.org/http://perldoc.perl.org/index-modules-A.htmlhttp://jobs.perl.org/http://perldoc.perl.org/index-modules-D.htmlhttp://perldoc.perl.org/index-modules-H.htmlhttp://perldoc.perl.org/preferences.htmlhttp://perldoc.perl.org/perlvar.htmlhttp://perldoc.perl.org/index-modules-N.htmlhttp://perldoc.perl.org/index-modules-L.htmlhttp://blogs.perl.org/http://perldoc.perl.org/index-language.htmlhttp://perldoc.perl.org/index-modules-E.htmlhttp://perldoc.perl.org/index-modules-O.htmlhttp://news.perlfoundation.org/http://perldoc.perl.org/perlfunc.htmlhttp://perldoc.perl.org/index-modules-B.htmlhttp://perldoc.perl.org/functions/sprintf.htmlhttp://perldoc.perl.org/index-overview.htmlhttp://perldoc.perl.org/index-modules-X.htmlhttp://www.perl.org/get.htmlhttp://ironman.enlightenedperl.org/http://learn.perl.org/http://perldoc.perl.org/index-modules-P.htmlhttp://perldoc.perl.org/index-modules-S.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/index-pragmas.htmlhttp://perldoc.perl.org/index-modules-F.htmlhttp://perldoc.perl.org/index-utilities.htmlhttp://www.yapc.org/http://perldoc.perl.org/index-modules-G.htmlhttp://perldoc.perl.org/http://perldoc.perl.org/index-licence.htmlhttp://perldoc.perl.org/index-history.htmlhttp://perldoc.perl.org/index-functions-by-cat.htmlhttp://perldoc.perl.org/index-modules-T.htmlhttp://search.cpan.org/http://perldoc.perl.org/index-modules-M.htmlhttp://perldoc.perl.org/perlop.htmlhttp://perldoc.perl.org/index-functions.html

  • 1/15/2015 sprintfperldoc.perl.org

    http://perldoc.perl.org/functions/sprintf.html 2/7

    Forexample:

    1. #Formatnumberwithupto8leadingzeroes2. $result=sprintf("%08d",$number);3.4. #Roundnumberto3digitsafterdecimalpoint5. $rounded=sprintf("%.3f",$number);

    Perldoesitsownsprintfformatting:itemulatestheCfunctionsprintf(3),butdoesn'tuseitexceptforfloatingpointnumbers,andeventhenonlystandardmodifiersareallowed.Nonstandardextensionsinyourlocalsprintf(3)arethereforeunavailablefromPerl.

    Unlikeprintf,sprintfdoesnotdowhatyouprobablymeanwhenyoupassitanarrayasyourfirstargument.Thearrayisgivenscalarcontext,andinsteadofusingthe0thelementofthearrayastheformat,Perlwillusethecountofelementsinthearrayastheformat,whichisalmostneveruseful.

    Perl'ssprintfpermitsthefollowinguniversallyknownconversions:

    1. %%apercentsign2. %cacharacterwiththegivennumber3. %sastring4. %dasignedinteger,indecimal5. %uanunsignedinteger,indecimal6. %oanunsignedinteger,inoctal7. %xanunsignedinteger,inhexadecimal8. %eafloatingpointnumber,inscientificnotation9. %fafloatingpointnumber,infixeddecimalnotation

    10. %gafloatingpointnumber,in%eor%fnotation

    Inaddition,Perlpermitsthefollowingwidelysupportedconversions:

    1. %Xlike%x,butusinguppercaseletters2. %Elike%e,butusinganuppercase"E"3. %Glike%g,butwithanuppercase"E"(ifapplicable)4. %banunsignedinteger,inbinary5. %Blike%b,butusinganuppercase"B"withthe#flag6. %papointer(outputsthePerlvalue'saddressinhexadecimal)7. %nspecial:*stores*thenumberofcharactersoutputsofar8. intothenextargumentintheparameterlist

    Finally,forbackward(andwedomean"backward")compatibility,Perlpermitstheseunnecessarybutwidelysupportedconversions:

    1. %iasynonymfor%d2. %Dasynonymfor%ld3. %Uasynonymfor%lu4. %Oasynonymfor%lo5. %Fasynonymfor%f

    Notethatthenumberofexponentdigitsinthescientificnotationproducedby%e,%E,%gand%Gfornumberswiththemodulusoftheexponentlessthan100issystemdependent:itmaybethreeorless(zeropaddedasnecessary).Inotherwords,1.23timestentothe99thmaybeeither"1.23e99"or"1.23e099".

    Betweenthe%andtheformatletter,youmayspecifyseveraladditionalattributescontrollingtheinterpretationoftheformat.Inorder,theseare:

    http://perldoc.perl.org/functions/if.htmlhttp://perldoc.perl.org/functions/sprintf.htmlhttp://perldoc.perl.org/functions/next.htmlhttp://perldoc.perl.org/functions/sprintf.htmlhttp://perldoc.perl.org/functions/sprintf.htmlhttp://perldoc.perl.org/functions/sprintf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/sprintf.html

  • 1/15/2015 sprintfperldoc.perl.org

    http://perldoc.perl.org/functions/sprintf.html 3/7

    formatparameterindex

    Anexplicitformatparameterindex,suchas2$.Bydefaultsprintfwillformatthenextunusedargumentinthelist,butthisallowsyoutotaketheargumentsoutoforder:

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

    flags

    oneormoreof:

    1. spaceprefixnonnegativenumberwithaspace2. +prefixnonnegativenumberwithaplussign3. leftjustifywithinthefield4. 0usezeros,notspaces,torightjustify5. #ensuretheleading"0"foranyoctal,6. prefixnonzerohexadecimalwith"0x"or"0X",7. prefixnonzerobinarywith"0b"or"0B"

    Forexample:

    1. printf'',12;#prints""2. printf'',12;#prints""3. printf'',12;#prints""4. printf'',12;#prints""5. printf'',12;#prints""6. printf'',12;#prints""7. printf'',12;#prints""8. printf'',12;#prints""9. printf'',12;#prints""

    10. printf'',12;#prints""

    Whenaspaceandaplussignaregivenastheflagsatonce,aplussignisusedtoprefixapositivenumber.

    1. printf'',12;#prints""2. printf'',12;#prints""

    Whenthe#flagandaprecisionaregiveninthe%oconversion,theprecisionisincrementedifit'snecessaryfortheleading"0".

    1. printf'',012;#prints""2. printf'',012345;#prints""3. printf'',0;#prints""

    vectorflag

    ThisflagtellsPerltointerpretthesuppliedstringasavectorofintegers,oneforeachcharacterinthestring.Perlappliestheformattoeachintegerinturn,thenjoinstheresultingstringswithaseparator(adot.bydefault).Thiscanbeusefulfordisplayingordinalvaluesofcharactersinarbitrarystrings:

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

    Putanasterisk*beforethevtooverridethestringtousetoseparatethenumbers:

    http://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.html

  • 1/15/2015 sprintfperldoc.perl.org

    http://perldoc.perl.org/functions/sprintf.html 4/7

    1. printf"addressis%*vX\n",":",$addr;#IPv6address2. printf"bitsare%0*v8b\n","",$bits;#randombitstring

    Youcanalsoexplicitlyspecifytheargumentnumbertouseforthejoinstringusingsomethinglike*2$vforexample:

    1. printf'%*4$vX%*4$vX%*4$vX',#3IPv6addresses2. @addr[1..3],":";

    (minimum)width

    Argumentsareusuallyformattedtobeonlyaswideasrequiredtodisplaythegivenvalue.Youcanoverridethewidthbyputtinganumberhere,orgetthewidthfromthenextargument(with*)orfromaspecifiedargument(e.g.,with*2$):

    1. printf"","a";#prints""2. printf"","a";#prints""3. printf"",6,"a";#prints""4. printf'',"a",6;#prints""5. printf"","long";#prints""(doesnottruncate)

    Ifafieldwidthobtainedthrough*isnegative,ithasthesameeffectastheflag:leftjustification.

    precision,ormaximumwidth

    Youcanspecifyaprecision(fornumericconversions)oramaximumwidth(forstringconversions)byspecifyinga.followedbyanumber.ForfloatingpointformatsexceptgandG,thisspecifieshowmanyplacesrightofthedecimalpointtoshow(thedefaultbeing6).Forexample:

    1. #theseexamplesaresubjecttosystemspecificvariation2. printf'',1;#prints""3. printf'',1;#prints""4. printf'',1;#prints""5. printf'',10;#prints""6. printf'',10;#prints""

    For"g"and"G",thisspecifiesthemaximumnumberofdigitstoshow,includingthosepriortothedecimalpointandthoseafteritforexample:

    1. #Theseexamplesaresubjecttosystemspecificvariation.2. printf'',1;#prints""3. printf'',1;#prints""4. printf'',100;#prints""5. printf'',100;#prints""6. printf'',100.01;#prints""7. printf'',100.01;#prints""8. printf'',100.01;#prints""

    Forintegerconversions,specifyingaprecisionimpliesthattheoutputofthenumberitselfshouldbezeropaddedtothiswidth,wherethe0flagisignored:

    1. printf'',1;#prints""2. printf'',1;#prints""3. printf'',1;#prints""4. printf'',1;#prints""

    sprintfPerl5version20.1documentationGototopShowrecentpages

    Home>Languagereference>Functions>sprintf

    Search

    http://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/index.htmlhttp://perldoc.perl.org/index-language.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/index-functions.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.html

  • 1/15/2015 sprintfperldoc.perl.org

    http://perldoc.perl.org/functions/sprintf.html 5/7

    5. printf'',1;#prints""6. printf'',1;#prints""7.8. printf'',1;#prints""9. printf'',1;#prints""

    10. printf'',1;#prints""11. printf'',1;#prints""12. printf'',1;#prints""13. printf'',1;#prints""

    Forstringconversions,specifyingaprecisiontruncatesthestringtofitthespecifiedwidth:

    1. printf'',"truncated";#prints""2. printf'',"truncated";#prints""

    Youcanalsogettheprecisionfromthenextargumentusing.*:

    1. printf'',1;#prints""2. printf'',6,1;#prints""

    Ifaprecisionobtainedthrough*isnegative,itcountsashavingnoprecisionatall.

    1. printf'',7,"string";#prints""2. printf'',3,"string";#prints""3. printf'',0,"string";#prints""4. printf'',1,"string";#prints""5.6. printf'',1,0;#prints""7. printf'',0,0;#prints""8. printf'',1,0;#prints""

    Youcannotcurrentlygettheprecisionfromaspecifiednumber,butitisintendedthatthiswillbepossibleinthefuture,forexampleusing.*2$:

    1. printf'',1,6;#INVALID,butinfuturewillprint2. #""

    size

    Fornumericconversions,youcanspecifythesizetointerpretthenumberasusingl,h,V,q,L,orll.Forintegerconversions(duoxXbiDUO),numbersareusuallyassumedtobewhateverthedefaultintegersizeisonyourplatform(usually32or64bits),butyoucanoverridethistouseinsteadoneofthestandardCtypes,assupportedbythecompilerusedtobuildPerl:

    1. hhinterpretintegerasCtype"char"or"unsigned2. char"onPerl5.14orlater3. hinterpretintegerasCtype"short"or4. "unsignedshort"5. jinterpretintegerasCtype"intmax_t"onPerl6. 5.14orlater,andonlywithaC99compiler7. (unportable)8. linterpretintegerasCtype"long"or9. "unsignedlong"

    10. q,L,orllinterpretintegerasCtype"longlong",11. "unsignedlonglong",or"quad"(typically12. 64bitintegers)13. tinterpretintegerasCtype"ptrdiff_t"onPerl

    http://perldoc.perl.org/functions/or.htmlhttp://perldoc.perl.org/functions/q.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/or.htmlhttp://perldoc.perl.org/functions/and.htmlhttp://perldoc.perl.org/functions/or.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/or.htmlhttp://perldoc.perl.org/functions/or.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/or.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/or.html

  • 1/15/2015 sprintfperldoc.perl.org

    http://perldoc.perl.org/functions/sprintf.html 6/7

    14. 5.14orlater15. zinterpretintegerasCtype"size_t"onPerl5.1416. orlater

    Asof5.14,noneoftheseraisesanexceptioniftheyarenotsupportedonyourplatform.However,ifwarningsareenabled,awarningoftheprintfwarningclassisissuedonanunsupportedconversionflag.Shouldyouinsteadpreferanexception,dothis:

    1. usewarningsFATAL=>"printf";

    Ifyouwouldliketoknowaboutaversiondependencybeforeyoustartrunningtheprogram,putsomethinglikethisatitstop:

    1. use5.014;#forhh/j/t/z/printfmodifiers

    YoucanfindoutwhetheryourPerlsupportsquadsviaConfig:

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

    Forfloatingpointconversions(efgEFG),numbersareusuallyassumedtobethedefaultfloatingpointsizeonyourplatform(doubleorlongdouble),butyoucanforce"longdouble"withq,L,orllifyourplatformsupportsthem.YoucanfindoutwhetheryourPerlsupportslongdoublesviaConfig:

    1. useConfig;2. print"longdoubles\n"if$Config{d_longdbl}eq"define";

    YoucanfindoutwhetherPerlconsiders"longdouble"tobethedefaultfloatingpointsizetouseonyourplatformviaConfig:

    1. useConfig;2. if($Config{uselongdouble}eq"define"){3. print"longdoublesbydefault\n";4. }

    Itcanalsobethatlongdoublesanddoublesarethesamething:

    1. useConfig;2. ($Config{doublesize}==$Config{longdblsize})&&3. print"doublesarelongdoubles\n";

    ThesizespecifierVhasnoeffectforPerlcode,butissupportedforcompatibilitywithXScode.Itmeans"usethestandardsizeforaPerlintegerorfloatingpointnumber",whichisthedefault.

    orderofarguments

    Normally,sprintf()takesthenextunusedargumentasthevaluetoformatforeachformatspecification.Iftheformatspecificationuses*torequireadditionalarguments,theseareconsumedfromtheargumentlistintheordertheyappearintheformatspecificationbeforethevaluetoformat.Whereanargumentisspecifiedbyanexplicitindex,thisdoesnotaffect

    http://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/print.htmlhttp://perldoc.perl.org/functions/use.htmlhttp://perldoc.perl.org/Config.htmlhttp://perldoc.perl.org/functions/eq.htmlhttp://perldoc.perl.org/functions/print.htmlhttp://perldoc.perl.org/functions/use.htmlhttp://perldoc.perl.org/functions/print.htmlhttp://perldoc.perl.org/functions/use.htmlhttp://perldoc.perl.org/functions/if.htmlhttp://perldoc.perl.org/functions/use.htmlhttp://perldoc.perl.org/functions/use.htmlhttp://perldoc.perl.org/functions/eq.htmlhttp://perldoc.perl.org/Config.htmlhttp://perldoc.perl.org/functions/print.htmlhttp://perldoc.perl.org/functions/or.htmlhttp://perldoc.perl.org/functions/use.htmlhttp://perldoc.perl.org/functions/if.htmlhttp://perldoc.perl.org/functions/or.htmlhttp://perldoc.perl.org/functions/q.htmlhttp://perldoc.perl.org/Config.html

  • 1/15/2015 sprintfperldoc.perl.org

    http://perldoc.perl.org/functions/sprintf.html 7/7

    thenormalorderforthearguments,evenwhentheexplicitlyspecifiedindexwouldhavebeenthenextargument.

    So:

    1. printf"",$a,$b,$c;

    uses$aforthewidth,$bfortheprecision,and$casthevaluetoformatwhile:

    1. printf'',$a,$b;

    woulduse$aforthewidthandprecision,and$basthevaluetoformat.

    Herearesomemoreexamplesbeawarethatwhenusinganexplicitindex,the$mayneedescaping:

    1. printf"%2\$d%d\n",12,34;#willprint"3412\n"2. printf"%2\$d%d%d\n",12,34;#willprint"341234\n"3. printf"%3\$d%d%d\n",12,34,56;#willprint"561234\n"4. printf"%2\$*3\$d%d\n",12,34,3;#willprint"3412\n"

    Ifuselocale(includinguselocale'not_characters')isineffectandPOSIX::setlocale()hasbeencalled,thecharacterusedforthedecimalseparatorinformattedfloatingpointnumbersisaffectedbytheLC_NUMERIClocale.SeeperllocaleandPOSIX.

    perldoc.perl.orgOfficialdocumentationforthePerlprogramminglanguage

    Contactdetails

    SitemaintainedbyJonAllen(JJ)

    DocumentationmaintainedbythePerl5Porters

    ManualOverviewTutorialsFAQsChanges

    ReferenceLanguageFunctionsOperatorsVariables

    ModulesModulesPragmasUtilities

    MiscLicenseInternalsPlatforms

    http://perldoc.perl.org/index-platforms.htmlhttp://perldoc.perl.org/index-utilities.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/index-pragmas.htmlhttp://perldoc.perl.org/perlvar.htmlhttp://perldoc.perl.org/index-overview.htmlmailto:[email protected]://perldoc.perl.org/index-history.htmlhttp://perldoc.perl.org/index-language.htmlhttp://perldoc.perl.org/perlop.htmlhttp://perldoc.perl.org/index-tutorials.htmlhttp://perldoc.perl.org/functions/use.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://lists.cpan.org/showlist.cgi?name=perl5-portershttp://perldoc.perl.org/index-functions.htmlhttp://perldoc.perl.org/index-faq.htmlhttp://perldoc.perl.org/perllocale.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/functions/printf.htmlhttp://perldoc.perl.org/index-internals.htmlhttp://perldoc.perl.org/index-licence.htmlhttp://perldoc.perl.org/index-modules-A.htmlhttp://perldoc.perl.org/POSIX.htmlhttp://perldoc.perl.org/functions/use.html