Commits

Shlomi Fish committed f5ba4e0

Add the named_sprintf function and more tests.

Comments (0)

Files changed (4)

modules/Text-Sprintf-Named/Build.PL

     license             => 'mit',
     dist_author         => 'Shlomi Fish <shlomif@cpan.org>',
     dist_version_from   => 'lib/Text/Sprintf/Named.pm',
+    requires => {
+        'Carp' => 0,
+        'Exporter' => 0,
+        'parent' => 0,
+        'strict' => 0,
+        'warnings' => 0,
+        'warnings::register' => 0,
+    },
     build_requires => {
         'Test::More' => 0,
         'Test::Warn' => '0.21',
     },
     add_to_cleanup      => [ 'Text::Sprintf::Named-*' ],
     create_makefile_pl => 'passthrough',
+    configure_requires => {
+        'Module::Build' => '0.36',
+    },
 );
 
 $builder->create_build_script();

modules/Text-Sprintf-Named/MANIFEST

 t/01-use.t
 t/02-override-param-retrieval.t
 t/03-incomplete.t
+t/04-procedural-iface.t
 t/boilerplate.t
 TODO
 t/pod-coverage.t

modules/Text-Sprintf-Named/lib/Text/Sprintf/Named.pm

 use Carp;
 use warnings::register;
 
+use parent 'Exporter';
+
+use vars qw(@EXPORT_OK);
+
+@EXPORT_OK = (qw( named_sprintf ));
+
 =head1 NAME
 
 Text::Sprintf::Named - sprintf-like function with named conversions
     # Returns "Hello John! Today is Thursday!"
     $formatter->format({args => {'name' => "John", 'day' => "Thursday"}});
 
+    # Or alternatively using the non-OOP interface:
+
+    use Text::Sprintf::Named qw(named_sprintf);
+
+    # Prints "Hello Sophie!" (and a newline).
+    print named_sprintf("Hello %(name)s!\n", { name => 'Sophie' });
+
+    # Same, but with a flattened parameter list (not inside a hash reference)
+    print named_sprintf("Hello %(name)s!\n", name => 'Sophie');
+
 =head1 DESCRIPTION
 
 Text::Sprintf::Named provides a sprintf equivalent with named conversions.
     return sprintf($format, @args);
 }
 
+=head2 named_sprintf($format, {%parameters})
+
+=head2 named_sprintf($format, %parameters)
+
+This is a convenience function to directly format a string with the named
+parameters, which can be specified inside a (non-blessed) hash reference or
+as a flattened hash. See the synopsis for an example.
+
+=cut
+
+sub named_sprintf
+{
+    my ($format, @args) = @_;
+
+    my $params;
+    if (! @args)
+    {
+        $params = {};
+    }
+    elsif (ref($args[0]) eq "HASH")
+    {
+        $params = shift(@args);
+    }
+    else
+    {
+        $params = {@args};
+    }
+
+    return 
+        Text::Sprintf::Named->new({ fmt => $format})
+                            ->format({args => $params});
+}
+
 =head1 AUTHOR
 
 Shlomi Fish, C<< shlomif@cpan.org >> , L<http://www.shlomifish.org/>

modules/Text-Sprintf-Named/t/04-procedural-iface.t

+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More tests => 1;
+
+use Text::Sprintf::Named qw(named_sprintf);
+
+{
+    # TEST
+    is (
+        named_sprintf('Hello %(name)s!', { name => "Sophie", }),
+        'Hello Sophie!',
+    );
+}