algebaric operations on a RegEx?

Madison Kelly linux-5ZoueyuiTZhBDgjK7y7TUQ at public.gmane.org
Sun Apr 5 02:50:06 UTC 2009


matt.price-H217xnMUJC0sA/PxXw9srA at public.gmane.org wrote:
> hi all,
> 
> I want to quickly play with some numeric values in an xml file (xbmc's 
> Fontxml files, of which there are often a number in any given skin).  
> what I need to do is find lines like:
> <size>13</size> and augment or decrement the values by a set number.  so 
> i'd like a command addsize, like this:
> 
> addsize 4 font.xml
> 
> that would change  the above to <size>17</size>
> 
> someone out there actually understand how to use perl, and willing to 
> show me how to do this?  thanks much,
> 
> matt
> 
> 
> -- 
> The Toronto Linux Users Group.      Meetings: http://gtalug.org/
> TLUG requests: Linux topics, No HTML, wrap text below 80 columns
> How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists

I am not sure if this is what you're looking for, but at this hour on a 
Saturday it's a minor miracle I can do anything. :)

----------
#!/usr/bin/perl

use strict;
use warnings;

# Can read this from ARGV if you wish
my $inc=4;
# Can read this from a file, if you wish
my $source=q|
<size>4</size>
<size>13</size>
<size>20</size>
<size>25</size>
|;

# Show what I am starting with, to follow along.
print "> source: [$source], increment: [$inc]\n";

# Loop through my source, pulling each matching XML element out.
foreach my $xml ($source=~/<size>\d+<\/size>/g)
{
	# Make a copy for the later regex.
	my $old_xml=$xml;
	
	# This is messy, but in short, 'split' returns ("", $num), the
	# (...)[1] simply returns the second element from the split and
	# adds the increment value in one line.
	my $num=((split/<size>(\d+)<\/size>/, $xml)[1])+$inc;

	# Modify my current XML element with the new string.
	$xml=~s/<size>(\d+)<\/size>/<size>$num<\/size>/g;

	# And now replace my old XML element with my incremented one in
	# the source.
	$source=~s/$old_xml/$xml/s;
}

# Show that we're done.
print "< source: [$source]\n";
exit(0);
----------

This may need tweaking to be more flexible with your source XML 
formatting, but hopefully it'll get you started.

Sorry, I wasn't able to do the math in-line, but it certainly may be 
possible with the right magical mix of match-stick-foo.

madi
--
The Toronto Linux Users Group.      Meetings: http://gtalug.org/
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists





More information about the Legacy mailing list