Why aren't newlines printed in this Perl code?

I have a simple Perl code:

#!/usr/bin/perl use strict; # not in the OP, recommended use warnings; # not in the OP, recommended my $val = 1; for ( 1 .. 100 ) { $val = ($val * $val + 1) % 8051; print ($val / 8050) . " \n"; } 

But when I started it, output:

 bash-3.2$ perl ./rand.pl 0.0002484472049689440.000621118012422360.003229813664596270.08409937888198760.92 ... <snipped for brevity> ... 2919250.9284472049689440.3526708074534160.1081987577639750.2295652173913040.1839 751552795030.433540372670807bash-3.2$ 

Am I doing something wrong?

+1
source share
3 answers

C:\> perldoc -f print :

Also, be careful not to follow typing a keyword with a left bracket if you do not want the right bracket to stop printing arguments - insert a + or put parentheses around all arguments.

Therefore, you need to:

 print( ($val / 8050) . "\n" ); 

or

 print +($val / 8050) . "\n"; 

The statement that you print the result of $val / 8050 , then combines the "\n" with the return value of print and then discards the resulting value.

By the way, if you:

 use warnings; 

then perl will tell you:

  print (...) interpreted as function at t.pl line 5.
    Useless use of concatenation (.) Or string in void context at t.pl line 5.
+18
source

This is more of a comment than an answer, but I do not know how to do this, and this question has already been answered.

Note that using say instead of printing neatly wraps the whole problem. I.e

 #!/usr/bin/perl use 5.010; use strict; use warnings; my $val = 1; for ( 1 .. 100 ) { $val = ($val * $val + 1) % 8051; say ($val / 8050); } 

works as intended, even if the problem does not occur. I still wonder how useful the words are, given its tiny difference.

+3
source

It is possible that the string is interpreted as follows

 (print($val / 8050)) . " \n"; 

i.e. parentheses are used as delimiters for the function argument list, with ". \ n" silently discarded. Try:

  print( ($val/8050) . "\n" ); 
0
source

Source: https://habr.com/ru/post/906158/


All Articles