Skip to content

Instantly share code, notes, and snippets.

@masak
Created December 1, 2009 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masak/246434 to your computer and use it in GitHub Desktop.
Save masak/246434 to your computer and use it in GitHub Desktop.
Unwrapping the second gift brought to you by Perl 6 this Advent, we find... a
method named C<.fmt>.
If you're familiar with C<sprintf>, you'll feel right at home with C<.fmt>. If
you haven't heard about C<sprintf> before, or if you've heard of it but are a
bit fuzzy on the details, you might want to skim the L<perldoc
page|http://perldoc.perl.org/functions/sprintf.html>. Don't drown in it,
though; it's longish. Just savour it.
Back to C<.fmt>, C<sprintf>'s spunky little sister. Here are a few ways to use
C<.fmt> to format strings and integers.
say 42.fmt('%+d') # '+42'
say 42.fmt('%4d') # ' 42'
say 42.fmt('%04d') # '0042'
say :16<1337f00d>.fmt('%X') # '1337F00D'
All this is good and well, but not really more than a shorter method form of
C<sprintf>. Big deal, right?
What I haven't told you yet is that C<.fmt> is overloaded, and works
differently on arrays (or more precisely, lists):
say <huey dewey louie>.fmt # 'huey dewey louie'
say <10 11 12>.fmt('%x') # 'a b c'
say <1 2 3>.fmt('%02d', '; ') # '01; 02; 03'
Similarly, it's overridden on hashes (or rather, maps):
say { foo => 1, bar => 2 }.fmt # 'foo 1
# bar 2'
say { Apples => 5, Oranges => 10 }.fmt('%s cost %d euros')
# 'Apples cost 5 euros
# Oranges cost 10 euros'
say { huey => 1, dewey => 2, louie => 3 }.fmt('%s', ' -- ')
# 'huey -- dewey -- louie'
The way hashing works may give your output a different order than the ones
shown above. Oh, and there's an overloaded C<.fmt> for pairs as well, but
it works analogously to the one for hashes.
C<.fmt> is a useful little tool to have when you want to change some value,
or an array or a hash of values, into to some given format. It's like
C<sprintf>, but tailored to Do What You Mean for arrays and hashes, too.
There's only one risk in all of this: Perl 6 might soil the reputation of
the Perl family of languages by simply being to darn readable. In order
to counter this risk, I leave a small parting gift in the form of a
simple-but-dense Christmas tree printing Perl 6 one liner:
$ perl6 -e 'say " "x 9-$_,"#"x($_*2-1)for 0..9,2xx 3'
#
###
#####
#######
#########
###########
#############
###############
#################
###
###
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment