in reply to search and replace

Next thing that's a little curious it the regex you compile for subsitution.  With the other regex fixed (e.g. my ( $key, $val ) = /^(\d+)\s+(\S+)/), you'd have:

([cross-referencereferencecross]{5,15})

The character class [...] is almost certainly not what you want.

Anyway, why not simply do a hash lookup using the value of the (chomp'ed) $line, such as "cross-reference"?  Something like

while (my $line = <INFILE>) { chomp($line); print $dict{$line} || $line, "\n"; }

Replies are listed 'Best First'.
Re^2: search and replace
by Anonymous Monk on Apr 03, 2009 at 13:57 UTC
    I modified the %dict reg exp as this and now its fine but still i get the error like this:
    Invalid [] range "s-r" in regex; marked by <-- HERE in m/\b([cross-r < +-- HERE eferencereferencecross]{5,15})\b/

      That's because of the curious character class :)

      Within a character class you can use "-" to declare ranges, such as [a-z], but as "s" is later in the alphabet than "r" (somewhat simplified, but I won't go into unicode, locales and stuff here...), the range is invalid.

      I'm not going to elaborate on how to fix this, because I'm not convinced yet, that you need this regex at all...

Re^2: search and replace
by Anonymous Monk on Apr 03, 2009 at 14:10 UTC
    the main purpose is to find all words that are seperated by space from my INFILE and replace them by their index. in your method its could work if it is one word per line.
      ...all words that are seperated by space...

      Ah... something you didn't mention in your OP.

      In this case, you could do:

      while (my $line = <INFILE>) { $line =~ s/(\S+)/$dict{$1} || $1/eg; print $line; }

      In case zero is a valid index, too, you'd need

      $line =~ s/(\S+)/defined $dict{$1} ? $dict{$1} : $1/eg;

      Or, if you're using Perl 5.10, you could write instead

      $line =~ s|(\S+)|$dict{$1} // $1|eg;