You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.
print $ids
should be a fairly hard statement to mess up, but it is possible. Possible reasons:
$ids
is undefined. Gives the warning undefined value in print
$ids
is out of scope. With use
strict
, gives fatal warning Global
variable $ids needs explicit package
name
, and otherwise the undefined
warning from above.print $ids $nIds
,
in which case perl thinks that $ids
is supposed to be a filehandle, and
you get an error such as print to
unopened filehandle
.Explanations
1: Should not happen. It might happen if you do something like this (assuming you are not using strict
):
my $var;
while (<>) {
$Var .= $_;
}
print $var;
Gives the warning for undefined value, because $Var
and $var
are two different variables.
2: Might happen, if you do something like this:
if ($something) {
my $var = "something happened!";
}
print $var;
my
declares the variable inside the current block. Outside the block, it is out of scope.
3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings
.
4: Also a common mistake. There are a number of ways to correctly print two variables in the same print
statement:
print "$var1 $var2"; # concatenation inside a double quoted string
print $var1 . $var2; # concatenation
print $var1, $var2; # supplying print with a list of args
Lastly, some perl magic tips for you:
use strict;
use warnings;
# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;
# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;
my $ids = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";
Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.
Variations:
print "@file"
is equivalent to
$ids = join(' ',@file); print $ids;
$#file
will return the last index
in @file
. Since arrays usually start at 0,
$#file + 1
is equivalent to scalar @file
. You can also do:
my $ids;
do {
local $/;
$ids = <$fh>;
}
By temporarily "turning off" $/
, the input record separator, i.e. newline, you will make <$fh>
return the entire file. What <$fh>
really does is read until it finds $/
, then return that string. Note that this will preserve the newlines in $ids
.
Line-by-line solution:
open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
chomp;
$ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.