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

Hi, I have an xml file at a location (ex: c:\temp\var.xml). In this file, there are several scalar variables in a single line. Scalars with one space between them. For example, file text looks like this:

$foo='abc' $id=12 $text_code='tech' $task_number=4 $bar='xyz' $coo="nzy" $crew='eleven'

My question: How can I get the value of $task_number from the above file. This value should be considered unknown and is a digit 1 to 9. I tried using the below part of the code but it didn't work. Thanks for any input in advance.

my $file="c:\\temp\\var.xml"; my $line; my $task_number; if(-e $file){ open(READ, "<$file")|| die "cannot open file\n\n"; while($line=<READ>){ my @array = split(/\s/,$line); my $task_number =~/\$task_number=(\d)/, @array; print $1"\n\n"; } close (READ); } #Then use that $1 value for something else.

Replies are listed 'Best First'.
Re: Get the value of a scalar variable from a file
by NetWallah (Canon) on Sep 10, 2013 at 01:46 UTC
    You are not using @array, so delete it. You need to understand the difference between list and scalar contexts.

    Try this:

    my ($task_number) = $line=~/\$task_number=(\d)/;
    Note the (parens) around $task_number - these provide a LIST context.

    Also, the match performed is on the $line variable.

                 My goal ... to kill off the slow brain cells that are holding me back from synergizing my knowledge of vertically integrated mobile platforms in local cloud-based content management system datafication.

Re: Get the value of a scalar variable from a file
by ww (Archbishop) on Sep 10, 2013 at 04:20 UTC

    ALT (AKA 'Tim Toady') and ignoring your problems with file handling, if you want to get all your names and values at one swell foop:

    #!/usr/bin/perl -w use 5.016; #1053134 my ($item, @subarr); my $line=<DATA>; chomp $line; my @arr = split /\s/, $line; for $item(@arr) { @subarr= split /=/, $item; print "name: $subarr[0] "; say " value: $subarr[1] \n"; } __DATA__ $foo='abc' $id=12 $text_code='tech' $task_number=4 $bar='xyz' $coo="nz +y" $crew='eleven'

    Upon execution, you'll see this:

    C:\>1053134.pl name: $foo value: 'abc' name: $id value: 12 name: $text_code value: 'tech' name: $task_number value: 4 name: $bar value: 'xyz' name: $coo value: "nzy" name: $crew value: 'eleven'

    If you didn't program your executable by toggling in binary, it wasn't really programming!