String::Substitution - Simple runtime string substitution functions
version 1.001
use String::Substitution -copy; my $subbed = gsub($string, $pattern, $replacement);
This module is a collection of functions to enable (global) substitution on a string using a replacement string or function created at runtime.
It was designed to take in the string, pattern, and replacement string from input at runtime and process the substitution without doing an eval.
eval
The replacement string may contain [numbered] match vars ($1 or ${1}) which will be interpolated (by using another s/// rather than eval).
$1
${1}
s///
The sub_* and gsub_* functions come in three variants:
sub_*
gsub_*
copy - Performs the substitution on a copy and returns the copy.
copy
modify - Modifies the variable in-place (just like $s =~ s///).
modify
$s =~ s///
context - Guess by the context which version to use. In void context execution will pass to the modify variant, otherwise pass to the copy variant. It's probably best to use copy or modify explicitly but the choice is yours.
context
Each version of each function takes three (scalar) arguments:
string on which to perform the substitution
search pattern (string or precompiled qr// pattern)
qr//
replacement (string or coderef)
Besides a string, the replacement can also be a coderef which will be called for each substitution. The regular pattern match variables will be available inside the coderef ($1) as you would expect.
# uppercase the first captured group in $pattern: gsub($string, $pattern, sub { uc $1 });
For convenience, however, the coderef will be passed the list returned from "last_match_vars" to allow you to do other pattern matching without losing those variables.
# can also use @_ (same as above) gsub($string, $pattern, sub { uc $_[1] }); # which is essentially: # $string =~ s/$pattern/ $codref->( last_match_vars() );/e # which allows you to get complicated (an example from t/functions.t): gsub(($string = 'mod'), '([a-z]+)', sub { (my $t = $1) =~ s/(.)/ord($1)/ge; "$_[1] ($1) => $t" }); # produces 'mod (d) => 109111100' # notice that $1 now produces 'd' while $_[1] still has 'mod'
See "FUNCTIONS" for more information about each individual substitution function.
$subbed = gsub_copy($string, $pattern, $replacement); # $string unchanged
Perform global substitution on a copy of the string and return the copy.
gsub_modify($string, $pattern, $replacement); # $string has been modified
Perform global substitution and modify the string. Returns the result of the s/// operator (number of substitutions performed if matched, empty string if not).
gsub_context($string, $pattern, $replacement); # $string has been modified $subbed = gsub_context($string, $pattern, $replacement); # $string unchanged
If called in a void context this function calls "gsub_modify". Otherwise calls "gsub_copy".
$interpolated = interpolate_match_vars($string, @match_vars);
Replaces any digit variables in the string with the corresponding elements from the match_vars array (returned from "last_match_vars").
Substitutes single and multiple digits such as $1 and ${12}.
${12}
A literal $1 can be escaped in the normal way. Any escaped (backslashed) characters will remain in the string and the backslash will be removed (also counts for doubled backslashes):
$string = 'the'; $pattern = 't(h)e'; # 'replacement' => 'output' # appearance when printed # '-$1-' => '-h-' # prints: -h- # '-\\$1-' => '-$1-' # prints: -$1- # '-\\\\$1-' => '-\\h-' # prints: -\h- # '-\\\\\\$1-' => '-\\$1-' # prints: -\$1- # '-\\x\\$1-' => '-x$1-' # prints: -x$1- # '-\\x\\\\$1-' => '-x\\h-' # prints: -x\h-
This function is used when the substitution functions receive a string as the replacement parameter. Essentially:
$interpolated = interpolate_match_vars($replacement, last_match_vars());
@match_vars = last_match_vars();
Return a list of the numeric match vars ($1, $2, ...) from the last successful pattern match.
$2
The first element of the array is undef to make it simple and clear that the digits correspond to their index in the array:
undef
@m = (undef, $1, $2); $m[1]; # same as $1 $m[2]; # same as $2
This can be useful when you want to save the captured groups from a previous pattern match so that you can do another (without losing the previous values).
This function is used by the substitution functions. Specifically, it's result is passed to the replacement coderef (which will be "interpolate_match_vars" if replacement is a string).
In the future the first element may contain something more useful than undef.
$subbed = sub_copy($string, $pattern, $replacement); # $string unchanged
Perform a single substitution on a copy of the string and return the copy.
sub_modify($string, $pattern, $replacement); # $string has been modified
Perform a single substitution and modify the string. Returns the result of the s/// operator (number of substitutions performed if matched, empty string if not).
sub_context($string, $pattern, $replacement); # $string has been modified $subbed = sub_context($string, $pattern, $replacement); # $string unchanged
If called in a void context this function calls "sub_modify". Otherwise calls "sub_copy".
This module exports nothing by default. All functions documented in this POD are available for export upon request.
This module uses Sub::Exporter which allows extra functionality:
There are predefined export groups corresponding to each of the variants listed above. Importing one (and only one) of these groups will rename the functions (dropping the suffix) so that the functions in your namespace will be named sub and gsub but will reference the variation you specified.
sub
gsub
Surely it is more clear with examples:
package Local::WithCopy; use String::Substitution -copy; # now \&Local::WithCopy::gsub == \&String::Substitution::gsub_copy package Local::WithModify; use String::Substitution -modify; # now \&Local::WithModify::gsub == \&String::Substitution::gsub_modify package Local::WithContext; use String::Substitution -context; # now \&Local::WithContext::gsub == \&String::Substitution::gsub_context
Note that String::Substitution does not actually have functions named sub and gsub, so you cannot do this:
String::Substitution
$subbed = String::Substitution::gsub($string, $pattern, $replacement);
But you are free to use the full names (with suffixes):
$subbed = String::Substitution::gsub_copy($string, $pattern, $replacement); String::Substitution::gsub_modify($string, $pattern, $replacement); String::Substitution::gsub_context($string, $pattern, $replacement);
That is the magic of Sub::Exporter.
If you are not satisfied with this see Sub::Exporter for other ways to get what you're looking for.
Probably a lot.
The replacement string only interpolates (term used loosely) numbered match vars (like $1 or ${12}). See "interpolate_match_vars" for more information.
This module does not save or interpolate $& to avoid the "considerable performance penalty" (see perlvar).
$&
String::Gsub
I tried to use this, but when I couldn't get it to install I decided to polish up an old function I had written a while back and try to make it reusable.
Plus I thought the implementation could be simpler.
You can find documentation for this module with the perldoc command.
perldoc String::Substitution
The following websites have more information about this module, and may be of help to you. As always, in addition to those websites please use your favorite search engine to discover more resources.
Search CPAN
The default CPAN search engine, useful to view POD in HTML format.
http://search.cpan.org/dist/String-Substitution
RT: CPAN's Bug Tracker
The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
http://rt.cpan.org/NoAuth/Bugs.html?Dist=String-Substitution
CPAN Ratings
The CPAN Ratings is a website that allows community ratings and reviews of Perl modules.
http://cpanratings.perl.org/d/String-Substitution
CPAN Testers
The CPAN Testers is a network of smokers who run automated tests on uploaded CPAN distributions.
http://www.cpantesters.org/distro/S/String-Substitution
CPAN Testers Matrix
The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.
http://matrix.cpantesters.org/?dist=String-Substitution
CPAN Testers Dependencies
The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.
http://deps.cpantesters.org/?module=String::Substitution
Please report any bugs or feature requests by email to bug-string-substitution at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=String-Substitution. You will be automatically notified of any progress on the request by the system.
bug-string-substitution at rt.cpan.org
http://github.com/rwstauner/String-Substitution
git clone http://github.com/rwstauner/String-Substitution
Randy Stauner <rwstauner@cpan.org>
This software is copyright (c) 2010 by Randy Stauner.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
To install String::Substitution, copy and paste the appropriate command in to your terminal.
cpanm
cpanm String::Substitution
CPAN shell
perl -MCPAN -e shell install String::Substitution
For more information on module installation, please visit the detailed CPAN module installation guide.