String::Substitution - Simple runtime string substitution functions
version 1.002
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
.
The replacement string may contain [numbered] match vars ($1
or ${1}
)
which will be interpolated (by using another s///
rather than eval
).
The sub_*
and gsub_*
functions come in three variants:
copy
- Performs the substitution on a copy and returns the copy.modify
- Modifies the variable in-place (just like$s =~ s///
).context
- Guess by the context which version to use. In void context execution will pass to themodify
variant, otherwise pass to thecopy
variant. It's probably best to usecopy
ormodify
explicitly but the choice is yours.
Each version of each function takes three (scalar) arguments:
- string on which to perform the substitution
- search pattern (string or precompiled
qr//
pattern) - 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}
.
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.
The first element of the array is undef
to make it simple and clear that the digits
correspond to their index in the array:
@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.
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:
$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).
-
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.
-
MetaCPAN
A modern, open-source CPAN search engine, useful to view POD in HTML format.
Please report any bugs or feature requests by email to bug-string-substitution at rt.cpan.org
, or through
the web interface at https://rt.cpan.org/Public/Bug/Report.html?Queue=String-Substitution. You will be automatically notified of any
progress on the request by the system.
https://github.com/rwstauner/String-Substitution
git clone https://github.com/rwstauner/String-Substitution.git
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.