I just picked up Perl yesterday (thanks to perlintro) and trying to figure out the best approach to do this. My first attempt uses regular expressions one line at a time – if it matches /nodeName.equals/, then it tries to match the following two lines, a) to pick up the method name for the “product” call and b) to make sure that the type is Integer or Double (there can be other types with different patterns). Here’s my Perl code:Original file ============= public Product getProduct(Node node) { // --- bunch of logic here --- if (nodeName.equals("ItemNum")) { product.setItemNumber( new Integer(StringUtils.parseInt(nodeValue, 0))); } if (nodeName.equals("AvgPrice")) { product.setAveragePrice( new Double(StringUtils.parseDouble(nodeValue, 0.0))); } } Converted file ============== public Product getProduct(Node node) { // --- bunch of logic here --- if (msg.isSetField(ItemNum.FIELD)) { product.setItemNumber(msg.getInt(ItemNum.FIELD)); } if (msg.isSetField(AvgPrice.FIELD)) { product.setAveragePrice(msg.getDouble(AvgPrice.FIELD)); } }
Is there a better way?while (<STDIN>) { if ($_ =~ /nodeName.equals/) { my $line1 = $_; my $line2 = <STDIN>; my $line3 = <STDIN>; if ($line3 =~ /new Integer/) { chomp($line1); $_ = "$line1$line2"; s/nodeName.equals\("(.*)"\).*product\.(.*)\(/msg.isSetFiel +d($1.FIELD)) {\n product.$2(msg.getInt($1.FIELD))\;/; print $_; } elsif ($line3 =~ /new Double/) { chomp($line1); $_ = "$line1$line2"; s/nodeName.equals\("(.*)"\).*product\.(.*)\(/msg.isSetFiel +d($1.FIELD)) {\n product.$2(msg.getDouble($1.FIELD))\;/; print $_; } else { print $line1; print $line2; print $line3; } } else { print $_; } }
Thanks for your help.
In reply to How to match and transform a multiline pattern? by nbhatia
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |