in reply to newbie regex question: substituting repeating occurences for different replacements

A regex like
my $row = "hello;this;is;a;test"; my $i = 1; print "row: $row\n"; $row =~ s/;/"<\/col". $i++ ."><col$i>"/eg; $row = "<col1>" . $row . "<col$i>"; print "row: $row\n";
That works. Not the prettiest thing in the world though.
I have to agree thought that regex is proboly not the best solution for this problem.
This one is kinda prettier :-)
my $row = "hello;this;is;a;test"; my $i = 1; print "row: $row\n"; @cols = split(/;/,$row); foreach $col (@cols) { $output .= "<col$i>$col</col$i>"; $i++} print "row: $output\n";
Notice that these all deal with just a single line though easily expanded to cover multiple lines.
Eric Hodges
  • Comment on Re: newbie regex question: substituting repeating occurences for different replacements
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: newbie regex question: substituting repeating occurences for different replacements
by Aristotle (Chancellor) on Jul 21, 2003 at 19:02 UTC
    Or in a pinch,
    while(<DATA>) { my $i; chomp; print join('', map { $i++; "<col$i>$_</col$i>" }, split /;/)."\n"; } __ hello;this;is;a;test this;is;another;simple;test

    Makeshifts last the longest.

      Cool. I always have a hard time figureing out when/how to use map. The more i see it the more it makes sense though. I think its partly because i'm not used to magical vars like $_ yet.

      Eric Hodges
        Well yes, avoiding $_ won't get you very far with map. :)

        Makeshifts last the longest.