Executing stored substitutions...

G

gibbering poster

Suppose I has some coderefs in an array, and wanted to loop through them
and apply them... more specifically to a string:

my @subs = (
{ s/\s+//g }, { s/-/ /g },
);

my $string = "\tJoe-Smith ";

for (@subs) {
local *_ = $string;
do &{$_}; # I know this is horribly wrong
}

print $string; # Want this to print "Joe Smith"


Can someone please show me the way here? Sorry in advance if I missed a
perldoc.

Thanks!

PS ... Is there a way to catch the return value of those substitions
(i.e. their success or failure)?
 
G

Gunnar Hjalmarsson

gibbering said:
Suppose I has some coderefs in an array, and wanted to loop
through them and apply them... more specifically to a string:

my @subs = (
{ s/\s+//g }, { s/-/ /g },

You need to say that they are code refs:

sub { s/\s+//g }, sub { s/-/ /g },
);

my $string = "\tJoe-Smith ";

for (@subs) {
local *_ = $string;
do &{$_}; # I know this is horribly wrong
}

You may want to try this:

for my $sub (@subs) {
local $_ = $string;
do &{$sub};
$string = $_;
}
 
K

ko

gibbering poster said:
Suppose I has some coderefs in an array, and wanted to loop through them
and apply them... more specifically to a string:

my @subs = (
{ s/\s+//g }, { s/-/ /g },
);

Those are (empty) hashrefs...
my $string = "\tJoe-Smith ";

for (@subs) {
local *_ = $string;
do &{$_}; # I know this is horribly wrong
}

print $string; # Want this to print "Joe Smith"

Can someone please show me the way here? Sorry in advance if I missed a
perldoc.

Thanks!

One way to do what you had in mind:

my @subs = (
sub { $_[0] =~ s#\s+##g },
sub { $_[0] =~ s#-# #g },
);

foreach ( @subs ) {
$_->($string);
}
print "$string\n";

But really, if you want to apply *all* the substitutions on the
string(s), put all of them in one sub...

If, on the other hand, you want to *selectively* perform the
substitutions (or run whatever code you like) use a dispatch table:

my $dt = {
whitespace => sub { $_[0] =~ s#\s+##g },
dashes => sub { $_[0] =~ s#-# #g },
# other coderefs...
};

foreach my $hrkey( qw[whitespace dashes] ) {
$dt->{$hrkey}->($string);
}
print "$string\n";

The following documentation are good reading in this case:

perlreftut
perldsc
perllol
PS ... Is there a way to catch the return value of those substitions
(i.e. their success or failure)?

From perlop:

s/PATTERN/REPLACEMENT/egimosx

Searches a string for a pattern, and if found, replaces that pattern
with the replacement text and returns the number of substitutions
made.

HTH - keith
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top