Exercise: split CGI


Given a string that looks like this:


my $str = 'fname=Foo&lname=Bar&email=foo@bar.com';

Create a hash where the keys are fname, lname, email or if the string looks like this


my $str = 'title=Stargates&year=2005&chapter=03&bitrate=128';

then create a hash where the keys are title, year, chapter, bitrate Use a single statement (with split) to achieve this.


examples/regex-perl/split_http_previous.pl
#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper;

my @input = (
    'fname=Foo&lname=Bar&email=foo@bar.com',
    'ip=127.0.0.1&machine=foobar',
);

foreach my $str (@input) {
    process($str);
}

sub process {
    my $str = shift;

    my @pairs = split /&/, $str;
    my %data;
    foreach my $p (@pairs) {
        my ($k, $v) = split /=/, $p;
        $data{$k} = $v;
    }
    print Dumper \%data;
}

$VAR1 = {
          'email' => 'foo@bar.com',
          'lname' => 'Bar',
          'fname' => 'Foo'
        };
$VAR1 = {
          'ip' => '127.0.0.1',
          'machine' => 'foobar'
        };