How do I use Perl's localtime with print to get the timestamp?

后端 未结 5 563
Happy的楠姐
Happy的楠姐 2020-12-20 10:58

I have used the following statements to get the current time.

  print \"$query executed successfully at \",localtime;
  print \"$query executed successfully          


        
相关标签:
5条回答
  • 2020-12-20 11:31

    Both the first and second return the values in the list context but they are probably not what you would expect. The use of parens around localtime simply won't do anything useful. But you can use the following code to get those returned list items separately:

    @list = ($sec,$min,$hour,$day,$mon,$year_1900,$wday,$yday,$isdst)=localtime;
    print join("\n",@list);
    
    0 讨论(0)
  • 2020-12-20 11:43

    The return value of localtime depends on the context. In list context it is a 9-element list, while in scalar context it is a ctime(3) value:

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
    my $now_string = localtime;  # e.g., "Thu Oct 13 04:54:34 1994"
    

    Now, print provides list context for its arguments. That's why print localtime outputs the numbers from the list (without any separator by default). You can force scalar context on localtime using either the . concatenation operator (like in your 3rd statement) or using scalar:

    print "".localtime;
    print scalar localtime;
    
    0 讨论(0)
  • 2020-12-20 11:46

    Perhaps the most important thing you can learn for programming in Perl, is context. Many built-in subroutines, and operators, behave differently depending on the context.

    print "$query executed successfully at ", localtime, "\n"; # list context
    print "$query executed successfully at ",(localtime),"\n"; # list context
    print "$query executed successfully at ". localtime, "\n"; # scalar context
    print "$query executed successfully at ".(localtime),"\n"; # scalar context
    
    print "$query executed successfully at ", scalar  localtime, "\n"; # scalar context
    print "$query executed successfully at ", scalar (localtime),"\n"; # scalar context
    

    This can be made clearer by splitting up the statements.

    my $time = localtime; # scalar context
    print "$query executed successfully at $time\n";
    
    my @time = localtime; # list context
    print "$query executed successfully at @time\n";
    
    0 讨论(0)
  • 2020-12-20 11:56

    scalar forces scalar context:

    print scalar localtime ();
    

    In the second example, it's clearly a list context so you're just getting a printout of the numbers in a row. For example, try

     print join (":", (localtime));
    

    and you'll see the numbers joined with a colon.

    0 讨论(0)
  • 2020-12-20 11:56

    If you want to get the timestamp of the current time, you can just use function time()

    0 讨论(0)
提交回复
热议问题