in reply to Global replace issue
Another possibility is to do just a single substitution, and keep track of what was matched.
#!/usr/bin/perl -w use strict; use warnings; my %subs = ( farenheit => sub { warn "Matched F with $^N\n"; return sprintf("%.u" , ($^N - 32) / 1.8) . 'C' }, celsius => sub { warn "Matched C with $^N\n"; return sprintf("%.u" , ($^N * 1.8) + 32) . 'F' }, ); my $WHAT; my $regex = qr/ (\d+)F (?{ $WHAT = 'farenheit' }) | (\d+)C (?{ $WHAT = 'celsius' }) /xi; my $html = do { local $/; <DATA> }; $html =~ s/$regex/$subs{$WHAT}->()/eg; warn $html; __DATA__ convert 180F to C convert 180C to F
Note that this uses a feature that's marked as EXPERIMENTAL in perlre, so be warned.
Also since there are now multiple captures in the same regex, $^N is more robust than using $1, $2 etc.
|
|---|