You ought to use split if you don't know the number of "words" (and by words I'm assuming you mean space-delimited text) ahead of time. Heck, even if you do you should use split. For example:
# Yes, I know how many "words" there are.
($word_one, $word_two, $word_three) = split " ", $sentence;
# No, I don't know how many words there are.
@words = split " ", $sentence;
The second example gives you an array filled with all the words in the sentence, in order. Now, if your question is how to put all the words into individually named scalar variables the answer is you can't. I mean, logically, how can you put n number of words into n number of scalars when n is unknown? You can't. That's why God invented the array, so you don't have to know. @words will be exactly as long as the number of words in your sentence, and you can get to each one whenver you wish, and have your nasty little way with them.
Gary Blackburn
Trained Killer | [reply] [d/l] |
Why don't you just split the @words array again, this time
in a loop, stating that each variable in the array becomes
its own ($word1 , $word2 , etc.) scalar ? The 1, 2, 3, you
can create with a simple increment. Does that contribute
to the solution ?
| [reply] |
@words = $string =~ m/(\w+)/g;
This will place each matching item into the array @words, the matching criteria is a greedy comparison on \w that gives a word character ie. not a space,tab,comma...etc.
The g at the the end of the regular expression is "global" so it will keep doing the match regardless of the string length. Regular Expressions are a very good place to start
whenever you want to do tricksy stuff with a string.
Good sources of learning are:
- perldoc perlre
- O'Reilly Owl Book - Mastering Regular Expressions.
I hope this helps ;^)
--
Brother Frankus. | [reply] |
Is it possible to do the opposite? Make an assignment of one scalar if a match is found in the elements of an array? I'm sure this syntax is wrong, but something like:
@terms = ("Word1","Word2","Word3");
$match = $1 if($lineFromSomeTextFile =~ /(^@terms)/);
I know the regular expression part is wrong, but is there some advanced Monk way of accomplishing this? What about grep? can that somehow be incorporated into the regex? | [reply] [d/l] |
| [reply] |
| [reply] [d/l] |
You might of wanted to test that statement out:
@words = qw($string);
puts the value '$string' into $words[0]
| [reply] [d/l] |
| [reply] |