quick question, since perl is big about lists on both sides of the equation, I'm wondering if there's a replace function that will replace using a list.
Say, you have a variable pulled from a spreadsheet, and you need to account for certain abnormalities, such as ', ' or ' ' (doublespace), or other combinations.
In VB, you can do this, but requires nested replace functions, which is really ugly and hard to manage. Makes the code look like this 'replace(replace(<string>,<search>,<replace>),<search>,<replace>)...' and so on until you cover all you need to cover.
This is where perl's list operations would come in handy, and just use a list or a hash (hash would be better choice). Does this exist or should somebody make it happen?
perl replace function
Page 1 of 13 Replies - 1599 Views - Last Post: 08 February 2013 - 02:06 AM
Replies To: perl replace function
#2
Re: perl replace function
Posted 03 February 2013 - 06:05 AM
Your VB example isn't really a list operation, it's simply passing the output of one function call as input to another function call without using an intermediate variable to store the result in between. In other words,
is the same as
but without using tmp.
So, with that clarified, yes, you can use a hash to replace multiple patterns in one fell swoop:
Output:
replace(replace(<string>,<search>,<replace>),<search>,<replace>)
is the same as
tmp = replace(<string>,<search>,<replace>) replace(tmp,<search>,<replace>)
but without using tmp.
So, with that clarified, yes, you can use a hash to replace multiple patterns in one fell swoop:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
my %replacement = (
',' => 'comma',
';' => 'semicolon',
'.' => 'dot',
string => 'sentence'
);
my $str = 'This string contains , . and ; characters';
my $pattern = '(' . join('|', map { quotemeta } keys %replacement) . ')';
$str =~ s/$pattern/$replacement{$1}/g;
say $str;
Output:
This sentence contains comma dot and semicolon characters
#3
Re: perl replace function
Posted 07 February 2013 - 07:08 AM
Ok, haven't seen the join function yet. Thanks
#4
Re: perl replace function
Posted 08 February 2013 - 02:06 AM
Pwn, on 07 February 2013 - 03:08 PM, said:
Ok, haven't seen the join function yet. Thanks
You could also do it without using join, by setting
my $pattern = '(,|;|\.|string)';
which would have the exact same end result, but it has the disadvantage of having to manually update the value of $pattern whenever you add another entry to %replacement. That approach would also get pretty cumbersome if you had a large number of replacement targets, so I prefer the solution with join for being more flexible and maintainable.
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|