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

Hey everyone, I am fairly new to perl, and this is a pretty basic question. Lets say I have a sub called x. I know the data passed into sub will be 1 long string. How can I parse @_ (in sub x) into an array of strings.

Example:
If "This is a test" were passed to x, i would like to create an array that would be equivilent to this:
@text = ("This","is","a","test");
Thanks in advance
-James

Replies are listed 'Best First'.
Re: String to tokens
by japhy (Canon) on Jan 31, 2004 at 21:39 UTC
    You want to use the split() function. It's aptly named. It takes a pattern to split a string on, and the string to split. @chunks = split /\s+/, "thing with spaces in it"; If you don't know regexes yet, you'll probably want to study up on them.

    You could also use a special case of this function (as explained in its documentation): @chunks = split ' ', $string_to_split; Please read the docs for more information.

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
Re: String to tokens
by Zaxo (Archbishop) on Jan 31, 2004 at 21:42 UTC

    1. Don't call your sub 'x'. That's the name of a perl operator.
    2. You can use magical split to divide your text on whitespace:
      sub words { split " ", $_[0]; }
      That works by splitting the first argument given to the sub. In a more complex sub, I would have shifted the first argument into a temporary variable.
    3. After Compline,
      Zaxo

Re: String to tokens
by Roger (Parson) on Jan 31, 2004 at 23:08 UTC
    An alternative is to use the @array = $str =~ /(pattern)/g idiom...
    sub foo { my $str = shift; my @text = $str =~ /(\S+)/g; ... } # call as foo("This is a test");