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

Greeting Monks,
I need to parse data like this: .command parameter
Here is what I got so far:
#!/usr/bin/perl #get command portion of data use strict; my ($stripped,$cmd,$cmd_loc,$cmd_locend); $stripped = ".command parameter"; $cmd_loc=index($stripped,"."); $cmd_locend=index($stripped,chr(32)); $cmd=substr($stripped,$cmd_loc,$cmd_locend++); print $cmd."\n";
This works just fine, but when I try to check if there is no parameter (I know it has to do with the chr(32), since there would be no space if it was only a command :P), but all the attempts to check for this have failed. I've tried checking to see it $cmd_locend == -1, etc.

I know this is a simple problem, but I guess I've been looking at the code to long, and have lost sight of it :\. Any help will be greatly appreciated!
Thanks
^jasper <jasper@wintermarket.org>

Title edit by tye

Replies are listed 'Best First'.
Re: Parsing
by VSarkiss (Monsignor) on Jun 11, 2002 at 15:10 UTC

    You don't have to inch along the string (you're used to programming in C, right? ;-) If the command and optional parameter are alphanumeric, just do this:

    if ($stripped =~ /\.(\w+)\s+(\w*)$/) { ($cmd, $parameter) = ($1, $2); # Other stuff.... }
    In general, if you want to take a string apart in Perl, regexes are much easier. More info at perlop (look for "quote-like operators") and perlre.

    HTH

      I was thinking about using regex, but havnt read much about it. Thanks for the help.
      p.s: ive never touched C :P
      ^jasper <jasper@wintermarket.org>
Re: Parsing
by Joost (Canon) on Jun 11, 2002 at 15:09 UTC
    You could also try using a regex for this:
    my ($cmd,$param) = ($stripped =~ /\.(\S+)\s*(\S*)/);
    -- Joost downtime n. The period during which a system is error-free and immune from user input.
Re: Parsing
by Jaspersan (Beadle) on Jun 11, 2002 at 15:05 UTC
    Ha, Just after I posted the first question I fix the problem :P. Oh well...
    Reply if you wish (if you can give me some pointers).
    Here is the 'fixed' code:
    #!/usr/bin/perl use strict; my $stripped = ".command"; my $cmd; my $cmd_loc=index($stripped,"."); my $cmd_locend=index($stripped,chr(32)); if ($cmd_locend > 1) { $cmd=substr($stripped,$cmd_loc,$cmd_locend++); } else { $cmd=substr($stripped,$cmd_loc); } print $cmd."\n";
    God I feel stupid now :)
    ^jasper <jasper@wintermarket.org>