Using perl to split a line that may contain whitespace

Posted by Tommy Fisk on Stack Overflow See other posts from Stack Overflow or by Tommy Fisk
Published on 2010-06-18T07:43:20Z Indexed on 2010/06/18 8:23 UTC
Read the original article Hit count: 404

Filed under:
|
|
|

Okay, so I'm using perl to read in a file that contains some general configuration data. This data is organized into headers based on what they mean. An example follows:

[vars]

# This is how we define a variable!
$var = 10;
$str = "Hello thar!";


# This section contains flags which can be used to modify module behavior
# All modules read this file and if they understand any of the flags, use them
[flags] 
  Verbose =       true; # Notice the errant whitespace!

[path]
WinPath = default; # Keyword which loads the standard PATH as defined by the operating system. Append  with additonal values.
LinuxPath = default;

Goal: Using the first line as an example "$var = 10;", I'd like to use the split function in perl to create an array that contains the characters "$var" and "10" as elements. Using another line as an example:

    Verbose    =         true;
    # Should become [Verbose, true] aka no whitespace is present

This is needed because I will be outputting these values to a new file (which a different piece of C++ code will read) to instantiate dictionary objects. Just to give you a little taste of what it might look like (just making it up as I go along):

define new dictionary
name: [flags]
# Start defining keys => values
new key name: Verbose
new value val: 10 
# End dictionary

Oh, and here is the code I currently have along with what it is doing (incorrectly):

sub makeref($)
{
    my @line = (split (/=/)); # Produces ["Verbose", "    true"];
}

© Stack Overflow or respective owner

Related posts about regex

Related posts about perl