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

Replies are listed 'Best First'.
Re: Search and replace with special characters
by Zaxo (Archbishop) on Oct 02, 2002 at 06:56 UTC

    You are using the default binding to $_ for the substitution without setting it. Also, the \Q\E pair in the replacement string are unwanted. Finally, the @pairs get overwritten with each iteration, which may or may not be OK depending on which string you want to modify. Assuming you want the replacement to be in @emotes,

    #!/usr/bin/perl -w use strict; my $images_url = '/images'; my @emotes = <DATA>; foreach my $entry (@emotes) { chomp $entry; my @pairs = split(/#####/, $entry); $entry =~ s/\Q$pairs[0]\E/<img src=\"$images_url\/emote_$pairs[1]. +gif\">/g; } print "@emotes",$/; __DATA__ oX#####skullandbones <;#####pie (o)#####goatse (~)#####ninja

    I also arranged for the image url to be quoted.

    After Compline,
    Zaxo

      One other minor thing that you might think about is adding a little complication to the regex in your split in case the emoticon ends with a trailing "#". Of course this assumes the name cannot start with a "#".
      while (<DATA>) { print join " <-> ", split /#####(?=[^#])/; } __DATA__ oX#####skullandbones <;#####pie (o)#####goatse (~)#####ninja :o)######clownwithbowtie __OUTPUT__ oX <-> skullandbones <; <-> pie (o) <-> goatse (~) <-> ninja :o)# <-> clownwithbowtie

      --

      flounder

Re: Search and replace with special characters
by io (Scribe) on Oct 02, 2002 at 13:27 UTC
    Why not use a hash?
    #!/usr/bin/perl -w use strict; my $html = <<END_OF_HTML; Hello! oX World! <;<;<;<; Hi! Samn! (~) END_OF_HTML my %emotes = map {split /#####|\n/} <DATA>; for my $entry(keys %emotes) { $html =~ s!\Q$entry\E!<img src="$emotes{$entry}.gif">!g; } print $html; __DATA__ oX#####skullandbones <;#####pie (o)#####goatse (~)#####ninja
    Note that im removing the trailing newline in the split operation, which is -ew- ugly.