Perl: Formatting String

By Xah Lee. Date: . Last updated: .

In Perl, if you want to print arrays or hashes for later reading into Perl program, you'll need to use “Data::Dumper” module.

#-*- coding: utf-8 -*-
# perl

use Data::Dumper;
$Data::Dumper::Indent = 0;      # set it to print in a compact way

@ss = (3, 4, 5);
%ss = qw(mary 17 jane 18 alice 19);
# qw for autoquote, same as ('mary' => 17, 'jane' => 18, 'alice' => 19)

print Dumper(\@ss), "\n";       # $VAR1 = [3,4,5];
print Dumper(\%ss), "\n";       # $VAR1 = {'jane' => 18,'alice' => 19,'mary' => 17};

For formatting strings, you can use “sprintf”, which is like other language's “format”.

Or, you can use “printf”, which is equivalent to print sprintf(FORMAT, LIST).

#-*- coding: utf-8 -*-
# perl

# integer
printf '%d', 1234;              # 「1234」
print "\n";

# padding by space
printf '%4d', 12;               # 「  12」
print "\n";

# float. 2 integer, 4 decimal
printf '%2.4f', 3.123456789;    # 「3.1235」
print "\n";

# string.
printf '%5s', 'cats';          # 「 cats」
print "\n";
printf '%2s', 'cats';          # 「cats」
print "\n";

printf ('%2d◇%6d◇%2.4f◇%s', 1234, 5678, 3.1415926, 'cats');
# prints 「1234◇  5678◇3.1416◇cats」

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex
  14. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. List Modules, Search Paths
  4. Write a Module
  5. Read / Write File
  6. Traverse Dir
  7. Find / Replace
  8. Complex Numbers
  9. System Call
  10. Compress / Decompress gzip
  11. Get Env Var
  12. GET Web Content
  13. Unicode 🐪
  14. Convert File Encoding
  15. Sort Unstable