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

I am writing a script that lets users replace the last submitted Napster searchable song with theirs. Napster hyperlinks require plusses where a space would be in the song title (and artist), but I don't want it displayed that way in the hyperlinked text (but naturally, I do want it in the hyperlink target).
open FILE, ">$now_song"; print FILE "<a href=nap:search\?artist=$FORM('songartist'}\&title= +$FORM{'songtitle'}>"; print FILE "$FORM{'songartist'} - $FORM{'songtitle'}</a>\n"; close(FILE);
I have separated the hyperlink into two PRINT statements, one for the part I want plusses instead of spaces, and one for the part I want spaces for spaces. Assume I know nothing, I am very new and am amazed I've accomplished this much :o) Thanks to any and everyone with a helpful word.

Replies are listed 'Best First'.
(jeffa) Re: Plusses obnox me
by jeffa (Bishop) on Apr 21, 2001 at 08:49 UTC
    Perl offers some very powerful regular expression operators, see perlman:perlre for further details should you feel the urge. In the meantime, you can turn spaces into plusses like so:
    my $str = "The Police"; $str =~ s/ /+/; # read between the slashes: space becomes + print "$str\n";
    Will yield 'The+Police' - but that only gets the first space, if the string was 'Guided By Voices' then the result would be 'Guided+By Voices' - that's why you need to specify a global replace:
    $str =~ s/ /+/g; # use this one ;)
    So, for your example you might want to store these values away before you print to your filehandle:
    my $escaped_artist = $FORM{songartist}; $escaped_artist =~ s/ /+/g; my $escaped_title = $FORM{songtitle}; $escaped_title =~ s/ /+/g; ... print FILE "<a href=nap ... (like you had before) print FILE "$escaped_artist - $escaped_title</a>\n";

    Jeff

    R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
    L-L--L-L--L-L--L-L--L-L--L-L--L-L--
    
      there is also tr/ /+/, the translation operator... which I believe is faster than regexp, (but of course only works to replace characters, not whole strings like a regexp)
                      - Ant
      Thank you kind sir. You can see the fruits of my (our!) labor at http://www.robotskull.com/cgi-bin/song.cgi
Re: Plusses obnox me
by Fastolfe (Vicar) on Apr 21, 2001 at 21:55 UTC
    Also consider using the CGI module's "escape" method (undocumented) for performing URI escapes like this. It's not that this is some proprietary Napster thing, it's the way things need to be escaped to make sense in the HTTP world. Consider the possibility that there will be a > in your data, or an &. Best to do something like this and your data is reasonably safe:
    s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;