I am just learning Perl, and am having a problem with something which seems like it should be so easy. Still . . . . I have read through a couple of books, including _Beginning Perl_ and _Picking Up Perl_, to no avail.
I am trying to read a file, then assign some information within a script. The problem comes in assigning. My file has three lines. The first line contains a list of names seperated by spaces; the next two lines contain numbers:
Doug Sandy Lois 0 1
In order to isolate the problem, I have created a simplified script:
You should really use the warnings and strict pragmas while developing your program to let perl help you find mistakes.
use warnings; use strict;
#read from file
open (CONTROL1, "<test.cont");
You should *ALWAYS* verify that the file opened correctly.
open CONTROL1, '<', 'test.cont' or die "Cannot open 'test.cont' $!";
@constants = <CONTROL1>; close (CONTROL1);
#parse
$names = @constants[0];
If you had had warnings enabled then perl would have complained about that.
@group = qw($names);
perldoc perlop [snip] qw/STRING/ Evaluates to a list of the words extracted out of STRING, using embedded whitespace as the word delimiters. It can be understood as being roughly equivalent to:
split(' ', q/STRING/);
the differences being that it generates a real list at compile time, and in scalar context it returns the last element in the list. So this expression:
qw(foo bar baz)
is semantically equivalent to the list:
'foo', 'bar', 'baz'
open (CONTROL2, ">test2.cont");
You should *ALWAYS* verify that the file opened correctly.
open CONTROL2, '>', 'test2.cont' or die "Cannot open 'test2.cont' $!";
print CONTROL2 "Names: $names"; print CONTROL2 "Group: @group"; close (CONTROL2);
The test2.cont file shows that $names is being set as I expected: to a string (Doug Sandy Lois). I assumed that @group = qw($names) would fill the array with the string of names. However, test2.cont shows that the value of @group is "$names". Obviously, my assumption was wrong.
So is there a way to directly fill the @group array with the string now stored in $names? Or do I have to split the string and fill the array in that manner?
You will have to split the string like:
my @group = split ' ', $names;
John -- use Perl; program fulfillment
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>