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

I'm trying to create a command prompt type where if you type in "ca something->somethingelse" it will split the ca from the rest, and then seperate the two strings. Then I want to store the something as a key in a hash I've already made keys and values for with somethingelse as the value. I already have code, but it's not working. I'm new to Perl, so it's probably something simple, but here it is...
if($current_input =~ /^ca\s\w+->\w+$/) { ($command, $temp) = split /\s/, $current_input, 2; ($key, $value) = split /->/, $temp, 2; $aliases{$key} = $value; }
thanx for your help - p u n k k i d

Replies are listed 'Best First'.
Re: Regex with -
by le (Friar) on Jul 21, 2000 at 01:21 UTC
    This should work:
    $aliases{$1} = $2 if $input =~ /^ca\s(\w+)->(\w+)$/;
Re: Regex with -
by btrott (Parson) on Jul 21, 2000 at 01:22 UTC
    What isn't working about it? It works for me; I added some code to dump out aliases (using Data::Dumper) and it contains the correct data:
    % test.pl ca foo->bar $VAR1 = { 'foo' => 'bar' };
    An alternate way of doing this, rather than using split, would be to use matching parens in the regular expression that you already have:
    if ($in =~ /^(\w{2})\s+(\w+)->(\w+)$/) { my($command, $key, $value) = ($1, $2, $3); $aliases{$key} = $value; }
    This would work if your commands are always 2 characters long, and if they always have the same format with the "->".
      When I try to access the value using $aliases{something} it's not giving me anything. The other part of the script is taking input from the user and accessing the hash with the key to produce the value. It works with the keys/values of the hash that I wrote into the script, but not the ones that the user adds.
      - p u n k k i d
Re: Regex with -
by qi3ber (Scribe) on Jul 21, 2000 at 19:02 UTC
    For the sake of efficiency, you will probably want to go with code that looks a lot like the snippet submitted by btrott although i think that this might be more similar to your initial posting. I added some extra whitespace matches, just because users are typically stupid.

    if ($current_input =~ /^\s*ca\s+(\w+)\s*->\s*(\w+)\s*$/) { my ( $key, $value ) = ($1, $2); $aliases{$key} = $value; }


    The other thought which occurs to me, is how are you attempting to retrieve the data back from the hash? You can always perform a sanity check to make sure that there is data in the hash.

    foreach my $key (keys $aliases) { print "\$aliases{$key} = $alias{$key}\n"; }