Formatting your Output
Perl enables you to produce formated output using print formats and the built-in function write.
Using Print Format
Defining | format MYFORMAT = # start with the format keyword =================================== Here is the text i want to display. =================================== . # terminated by a single dot |
Display a print format | $~ = "MYFORMAT"; # set the system variable $~ to the format you want to use format MYFORMAT = |
Displaying Valuesin a Print Format | $line = "hello this is a test program"; $line =~ s/[^aeiou]//g; $~ = "MYFORMAT"; format MYFORMAT = Note: the @<<<<< means six left justified characters |
There are a number of fields formats that can be used
Left-Justified output | @<<< # 4 left-justified characters ( (@=1 character) + (<<<=3 characters) ) = 4 characters total @<<<<< # 6 left-justified characters |
Right-Justified output | @>>> @>>>>> |
Centered output | @|||| # 4 centered characters |
Fixed-precision numeric | @##.## # 3 numbers before decimal point 2 numbers after example 345.78 |
Multiline text | @* # any length |
There are other formating utilies
Specifying a Page Number | $~ = "PAGE_FOOTER"; format PAGE_FOOTER = |
Set the page length | $= = 66; # system variable $= hold the page length |
Change the Header Print Format | $~ = "MYFORMAT"; $^ = "TOP_OF_PAGE"; write; format MYFORMAT = |
Balance formatting and removing blank lines | $string = ("this is a\n line of string to\n confuse outputting added a couple of blank lines \n"); $~ = "MYFORMAT"; format MYFORMAT = Note: the ^<< trys to fit as many lines as possible, @* will print as is including newlines |
Putting it all together | open (OUTFILE, ">file1"); |
Using printf
Perl borrows from the C language the printf function and is used just the same, the field specifiers are below
Single Character | %c |
Integer | %d |
Floating-point in scientific notation | %e |
Floating-point in normal fixed-point notation | %f |
Floating-point in compact format | %g |
Integer in octal | %o |
Character String | %s |
Unsigned integer | %u |
nteger in hex format | %x |
Examples | printf("The number is %d", $number); printf("amount: %20d", $salary); # 20 fields of characters (right justified) |