FloydATC has asked for the wisdom of the Perl Monks concerning the following question:
So, I threw together this little script to get the job done:
This did the job, because there were no other 11+ digit numbers in this particular XML file. Problem solved.#!/usr/bin/perl use strict; use warnings; use Digest::MD5 qw( md5_hex ); while (my $xml = <STDIN>) { $xml =~ s/(\d{11})/md5_hex($1)/eg; print $xml; }
But what if there were? What if I only wanted to change 11 digit numbers enclosed in a particular tag? Let's say I wanted to inject more than just a single sub?
This ofcourse doesn't work because there is no such variable as "$1md5_hex". And if I start throwing "s and .s in there, I'm just telling Perl to insert those characters into my output.$xml =~ s/(\<tag\>)(\d{11})(\<\/tag\>)/$1md5_hex($2)$3/eg;
Can someone point me in the right direction here? What if I really needed to substitute with a combination of static text and a sub? I can imagine ways of doing it manually ofcourse so that's beside the point. Can it be done using a simple regex substitution?
Or is the best/only solution in this case to write a "wrapper" sub to create the exact string to substitute with?
$xml =~ s/(\<tag\>)(\d{11})(\<\/tag\>)/transformed($1,$2,$3)/eg; ... sub transformed { my ($prefix,$number,$suffix) = @_ return $prefix . md5_sum($number) . $suffix; }
Time flies when you don't know what you're doing
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regex substitute with both a sub and other data
by tobyink (Canon) on Aug 23, 2013 at 10:35 UTC | |
by AnomalousMonk (Archbishop) on Aug 23, 2013 at 12:21 UTC | |
|
Re: Regex substitute with both a sub and other data
by choroba (Cardinal) on Aug 23, 2013 at 10:36 UTC | |
by FloydATC (Deacon) on Aug 23, 2013 at 10:41 UTC | |
|
Re: Regex substitute with both a sub and other data
by Laurent_R (Canon) on Aug 23, 2013 at 18:49 UTC |