Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print variables in Perl

Tags:

perl

I have some code that looks like

my ($ids,$nIds); while (<myFile>){     chomp;     $ids.= $_ . " ";     $nIds++; } 

This should concatenate every line in my myFile, and nIds should be my number of lines. How do I print out my $ids and $nIds?

I tried simply print $ids, but Perl complains.

my ($ids, $nIds) 

is a list, right? With two elements?

like image 246
monkeyking Avatar asked May 30 '11 22:05

monkeyking


People also ask

How do I print a variable in a string in Perl?

To print a variable as part of a a string, just use the Perl printing syntax as shown in this example: $name = 'Alvin'; print "Hello, world, from $name.

How do I print in Perl?

print() operator – print operator in Perl is used to print the values of the expressions in a List passed to it as an argument. Print operator prints whatever is passed to it as an argument whether it be a string, a number, a variable or anything. Double-quotes(“”) is used as a delimiter to this operator.


2 Answers

print "Number of lines: $nids\n"; print "Content: $ids\n"; 

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar"; 
like image 84
ysth Avatar answered Oct 03 '22 13:10

ysth


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:

  1. $ids is undefined. Gives the warning undefined value in print
  2. $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.
  3. You forgot a semi-colon at the end of the line.
  4. You tried to do 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. 
like image 36
TLP Avatar answered Oct 03 '22 13:10

TLP