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

Hi.. I've got a short Perl question... I want to take the contents of a variable called, say, $input
$input = "word+word+word";
and split it up, so that i can put something along the lines of the following into a variable, which we'll call $string
keyword1=word&keyword2=word&keyword3=word
I've drawn up some mock Perl code to help give a better idea of what i mean.
$string = ""; $wordnum = 0; $input = "word+word+word"; (@keywords) = split(/\+/, $input); foreach $keyword (@keywords){ $wordnum++; $string .= qq~keyword_$wordnum=$keyword~; }

Replies are listed 'Best First'.
Re: splitting contents of a variable ( not what you think!! )
by blakem (Monsignor) on Jan 28, 2002 at 04:49 UTC
    How about using the powers of join, map and split?
    #!/usr/bin/perl -wT use strict; my $input = "word+word+word"; my $i=1; my $string = join '&', map {"keyword".$i++."=$_"} split /\+/, $input; print "$string\n"; __END__ keyword1=word&keyword2=word&keyword3=word
    Reading that complicated line from bottom to top... First we split the string into pieces, then we map those pieces to the new format, finally we join them together with a new delimiter.

    Update: Just for kicks... this regex seems to work as well:

    my $i = ''; (my $string = $input) =~ s/(^|\+)/($i++&&'&')."keyword$i="/ge;

    -Blake

Re: splitting contents of a variable ( not what you think!! )
by Masem (Monsignor) on Jan 28, 2002 at 04:51 UTC
    You're close. You probably want to put all your strings into an array, then use the reverse of split, join to put your '&' into place. Continuing from your code:
    my @strings; foreach $keyword (@keywords){ $wordnum++; push @strings, "keyword_$wordnum=$keyword"; } my $string = join '&', @strings;

    -----------------------------------------------------
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
    "I can see my house from here!"
    It's not what you know, but knowing how to find it if you don't know that's important

Re: splitting contents of a variable ( not what you think!! )
by Juerd (Abbot) on Jan 28, 2002 at 11:13 UTC
    my $input = 'foo+bar+baz'; my $i = 1; my $string = join '&', map { 'keyword' . $i++ . '=' . $_ } split /\+/, + $input;

    This might be the first time you see map. It's not as hard as it looks: map BLOCK LIST evaluates BLOCK for every item of the given LIST, aliassing $_ to that item.
    In other words: map creates a list out of a list.

    So this is what happens: $input gets split, and the individual items are sent through map, which prefixes "keyword#=", increasing the number by one. Then, join joins them using supergl^W'&'. The result is put in $string.

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$