in reply to search and replace

What do you think of this code?

#!/usr/bin/perl use strict; my $old_string = "the dog chased my cat."; my ($new_string, $found_word); my %dict; while( <DATA> ) { my ($key, $val) = $_ =~ /^(\d)\s(\w+)/; $dict{$val} = $key; } chop( $old_string ); my @words = split( " ", $old_string); foreach my $i ( @words ) { foreach my $j ( keys %dict ) { if ( $j eq $i ) { $new_string = $new_string . "$dict{$j} "; $found_word++; } } $new_string = $new_string . "$i " if ($found_word == 0); $found_word = 0; } chop( $new_string ); print "$new_string."; __DATA__ 1 dog 2 cat 3 chased 4 the

Replies are listed 'Best First'.
Re^2: search and replace
by jwkrahn (Abbot) on Mar 17, 2009 at 19:11 UTC

    How about like this:

    #!/usr/bin/perl use warnings; use strict; my $old_string = 'the dog chased my cat.'; my %dict; while ( <DATA> ) { my ( $key, $val ) = /^(\d+)\s+(\w+)/; $dict{ $val } = $key; } my $cc = join '', keys %dict; my ( $min ) = my ( $max ) = map length, keys %dict; for ( map length, keys %dict ) { $min = $_ if $min > $_; $max = $_ if $max < $_; } my $pattern = qr/\b([$cc]{$min,$max})\b/; ( my $new_string = $old_string ) =~ s/$pattern/ exists $dict{ $1 } ? $ +dict{ $1 } : $1 /eg; print "$old_string\n$new_string\n"; __DATA__ 1 dog 2 cat 3 chased 4 the
      I defined it like this:
      #!/usr/bin/perl use warnings; use strict; open (DATA, "dic") || die "Error opening the input file\n"; print "Reading mapping file\n"; print "----------------------------\n"; open (INFILE, "trial.txt") || die "Error opening the input file\n"; print "Reading input file\n"; print "----------------------------\n"; my %dict; while (my $line = <INFILE>) { my $old_string = $line; while ( <DATA> ) { my ( $key, $val ) = /^(\d+)\s+(\w+)/; $dict{ $val } = $key; } my $cc = join '', keys %dict; my ( $min ) = my ( $max ) = map length, keys %dict; for ( map length, keys %dict ) { $min = $_ if $min > $_; $max = $_ if $max < $_; } my $pattern = qr/\b([$cc]{$min,$max})\b/; ( my $new_string = $old_string ) =~ s/$pattern/ exists $dict{ $1 } ? $ +dict{ $1 } : $1 /eg; print "$new_string\n"; } close (INFILE); close (DATA);
      but I get this error:
      Reading mapping file ---------------------------- Reading input file ---------------------------- april 1168 0.06781456 Use of uninitialized value in concatenation (.) or string at seek.pl l +ine 29, <DATA> line 19969. Use of uninitialized value in concatenation (.) or string at seek.pl l +ine 29, <DATA> line 19969. Unmatched [ in regex; marked by <-- HERE in m/\b([ <-- HERE ]{,})\b/ a +t seek.pl line 29, <DATA> line 19969.
      Not that 19969 is my last line in dictionary file. and also how can I ignore the cases in matching? for example in dictionary file April exists but april does not, so I tend to make it case insensetive. thanks in advance.
        I've solved the problem of errors but still dont know how to solve the problem with the case sensevity.