Look at one of the Tutorials here such as "Getting Started with Perl" to get started with Perl programming, and then work out how you think this should work. It is much easier (and more beneficial) to help you fix or improve your code than to just give you the answer.
Consider, too, how you intend to use the data you're reading, and also how you might write this program to solve this particular problem but also be useful for files of more than 2 lines.
| [reply] |
See perlintro. The following is almost entirely copied from that page, I've just added the chomp to remove the newlines and customized the print:
#!/usr/bin/env perl
use strict;
use warnings;
open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
chomp( my @lines = <$in> );
close $in or die "$in: $!";
print "Line 1: $lines[0]\n";
print "Line 2: $lines[1]\n";
| [reply] [d/l] |
Two questions: 1. Will the file always have exactly two lines? 2. Do you want two separate variables, with fixed names like $foo and $bar, is an array like in the above example acceptable, or do you maybe want to save them in a hash with certain keys?
| [reply] [d/l] [select] |
I would strongly advise that, instead of “creating variables,” you should always create “keys in a hash.” The namespace of “variables in the currently-running program” should never be polluted by anything that is read from an external data-source. (This was probably the worst idea that PHP ever came up with ...) The trouble is that, if the name matches an existing variable, and is unthinkingly permitted to replace it, the program will either be crashed or, infinitely worse, deliberately exploited. In any case, such a program can never be reliable.
You should write the program to read the file line-by-line, then, say, split() each line into “key” (formerly known as “variable-name” ...) and “value” components. Then, $hashref->{$key} = $value;. Now, the file can pretty-much contain anything that it wants, because the only thing that will actually be affected ... or that can possibly be affected, is: the set of keys in $hashref. Not the program’s own variable-pool.
| |
I think what jackierobs12 had in mind was to assign the two lines to two already defined variables (i.e., 'var1' and 'var2' from the OP) rather than creating new global variable symbols based on input data, which I agree is a Bad Idea.
Give a man a fish: <%-(-(-(-<
| [reply] [d/l] |