Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Hi, I'm completely new to PERL so sorry if this is a stupid question. What I want to happen is have text $oldstr replaced with $newstr and a counter (so $newstr text 1, 2, 3 for each instance of replacement) across a batch of files in a particular folder (although I'm only working on one file directly as yet). One of the problems I'm having is the counter is including the lines in between, so my replacement text is $newstr text 3, 9 11 etc. How do I get the counter to only add 1 when the $oldstr is found and replaced by the $newstr? any help much appreciated

use strict; open(FILE, "<test.xml") || die "File not found"; my @lines = <FILE>; close(FILE); my $oldstr = "core:para"; my $newstr = "core:para edpnum\-start\=\""; my @newlines; my $counter =0; foreach(@lines) { if ($oldstr =~ /core\:para/){ $counter = $counter +1; } $_ =~ s/$oldstr/$newstr$counter/g; push(@newlines,$_); } open(FILE, ">test.xml") || die "File not found"; print FILE @newlines; close(FILE);

In reply to search and replace plus counter by Harkers

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-03-19 03:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found