Why aren't newlines being printed in this Perl code?

前端 未结 3 1148
清歌不尽
清歌不尽 2020-12-12 04:17

I have some 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 ..         


        
相关标签:
3条回答
  • 2020-12-12 04:54

    It is possible that the line is interpreted as follows

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

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

     print( ($val/8050) . "\n" );
    
    0 讨论(0)
  • 2020-12-12 05:03

    This is more of a comment than an answer, but I don't know how else to make it and the question is already answered anyway.

    Note that using say instead of print neatly sidesteps the whole issue. That is,

    #!/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 without the issue even coming up. I'm still amazed at how useful say is, given it's such a tiny difference.

    0 讨论(0)
  • 2020-12-12 05:06

    C:\> perldoc -f print:

    Also be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print--interpose a + or put parentheses around all the arguments.

    Therefore, what you need is:

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

    or

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

    The statement you have prints the result of $val / 8050 and then concatenates "\n" to the return value of print and then discards the resulting value.

    Incidentally, 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.
    
    0 讨论(0)
提交回复
热议问题