cranberry13 has asked for the wisdom of the Perl Monks concerning the following question:

I am reading a file and finding all instances of a certain word.

What I would like to do is:

1) The first time I see the word I want to footnote it.
2) Any additional instance of the same word should be underlined.

How can I do this in a Regular Expression using the substitution operator ?

The line below will create a footnote for the first instance of the word gregarious:

$line =~ s/gregarious/\\footnote\{gregarious\}/im;

If the word appears again in the file, I would like it to underline it:

$line =~ s/gregarious/\\underline\{gregarious\}/;

Is there a way to combine these two statements and have the first instance of the word formatted differently from the others?

Replies are listed 'Best First'.
Re: Combining two Reg Expressions with substitution
by Enlil (Parson) on Nov 04, 2003 at 17:59 UTC
    Sure there is.
    use strict; use warnings; my $string = 'gregarious gregarious gregarious'; my $count = 0; $string =~ s/gregarious/$count++ ? "\\underline{gregarious}" : "\\foot +note{gregarious}"/ieg

    -enlil

Re: Combining two Reg Expressions with substitution
by Abigail-II (Bishop) on Nov 04, 2003 at 18:02 UTC
    I'd go for:
    $line =~ s/(gregarious)/\\underline{gregarious}/g && $line =~ s/\\underline\{(gregarious)\}/\\footnote{$1}/;

    Abigail

      But wouldn't that just work for a single line? The next line that contained gregarious would have its first occurrence footnoted. Which isn't what the OP was asking for. I think. Sometimes.

      No, wait, I see what it's doing now. OK, feel free to ignore me (which is usually a good idea).

        #!/usr/bin/perl use strict; use warnings; $_ = <<'--'; gregarious foo gregarious foo foo gregarious foo gregarious gregarious foo gregarious foo -- s/(gregarious)/\\underline{$1}/g && s/\\underline\{(gregarious)\}/\\footnote{$1}/; print; __END__ \footnote{gregarious} foo \underline{gregarious} foo foo \underline{gregarious} foo \underline{gregarious} \underline{gregarious} foo \underline{gregarious} foo

        Abigail