Skip to content

Instantly share code, notes, and snippets.

@barefootcoder
Last active December 14, 2015 16:59
Show Gist options
  • Save barefootcoder/5119064 to your computer and use it in GitHub Desktop.
Save barefootcoder/5119064 to your computer and use it in GitHub Desktop.
This is code lifted some time ago from an older version of Filter::Simple (by the Damian). I use it whenever I need to make substituions in code-like-strings, but I want to make sure I don't changes things inside quotes.
sub whatever
{
use Text::Balanced qw< extract_multiple extract_delimited >;
my ($string) = @_;
# this replaces all quoted strings with placeholders
my @quoted_strings;
$string = join('', map { ref $_ ? scalar((push @quoted_strings, $_), "{Q$#quoted_strings}") : $_ }
extract_multiple($string,
[
{ SQ => sub { extract_delimited($_[0], q{'}, '', q{'}) } },
{ DQ => sub { extract_delimited($_[0], q{"}, '', q{"}) } },
qr/[^'"]+/,
])
);
# ...
# (do whatever you want to $string)
# ...
# and this replaces the placeholders with the original quoted strings
$string =~ s/{Q(\d+)}/${$quoted_strings[$1]}/g;
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment