#!/usr/local/bin/perl -wl use strict; sub my_printf { my $text = shift; $text =~ s/\%(.)/&replace_arg($1,\@_)/ge; return $text; } sub replace_arg { # takes in a replacement 'code' and an arg list ref # converts the code, poping from the arg list as needed # if you have more then 3 possible codes, you might want to # impliment this as a hash of code refs (aka: closures) my ($code, $args) = @_; if ('a' eq $code) { # %a means flat substitution return shift @{$args}; } elsif ('b' eq $code) { # %b means length of the arg return length shift @{$args}; } elsif ('%' eq $code) { # %% means % return '%'; # note: no shift } # else... return "humina:$code?"; } print my_printf("foo %a bar %b", "baz", "baz"); print my_printf("oy %%9"); print my_printf("the %a is %% %b", "probability", "foo bar"); print my_printf("ignoring %%100 of the unused args", "unused arg"); __END__ foo baz bar 3 oy %9 the probability is % 7 ignoring %100 of the unused args
In reply to Re: Re: Accepting a template string and replacing placeholders the way printf does.
by hossman
in thread Accepting a template string and replacing placeholders the way printf does.
by ehdonhon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |