Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Perl File Parsing - My Code Works, but it's Ugly!

by golux (Chaplain)
on May 31, 2015 at 19:58 UTC ( [id://1128498]=note: print w/replies, xml ) Need Help??


in reply to Perl File Parsing - My Code Works, but it's Ugly!

Hi Nico,

One other suggestion concerning your escaping of underscores "_":

$outfolder = "REPORT_output\_$year\_$mon\_$mday\_\_$hour\_$min +\_$sec";

The underscore character doesn't need to be escaped like this everywhere in a string. If you were doing so to separate it from the preceding variable (ie. "$year\_$mon" in order to interpolate $year instead of $year_), there's another, more common way to do so which is arguably a little easier to read:

$outfolder = "REPORT_output_${year}_${mon}_${mday}__${hour}_${ +min}_$sec";

This syntax is also often used to separate variables from other chars which could be part of the variable name; eg.:

my $msg = "Hello world"; my $color = 101; # Red background print "\e[${color}m $msg \e[m\n"; # Embed $color in escape sequence
say  substr+lc crypt(qw $i3 SI$),4,5

Replies are listed 'Best First'.
Re^2: Perl File Parsing - My Code Works, but it's Ugly!
by aaron_baugher (Curate) on May 31, 2015 at 22:03 UTC

    Another option would be something like this, though whether it's more readable might be a matter of personal preference:

    my $outfolder = join '_', 'REPORT', 'output', $year, $mon, $mday, '', +$hour, $min, $sec;

    Aaron B.
    Available for small or large Perl jobs and *nix system administration; see my home node.

Re^2: Perl File Parsing - My Code Works, but it's Ugly!
by Anonymous Monk on Jun 01, 2015 at 10:22 UTC

    TIMTOWTDI:

    $outfolder = sprintf "REPORT_output_%d_%d_%d__%d_%d_%d", $year, $mon, $mday, $hour, $min, $sec;

    With the advantage that you could do something like:

    $outfolder = sprintf "REPORT_output_%04d_%02d_%02d__%02d_%02d_%02d", $year, $mon, $mday, $hour, $min, $sec;

    giving

    REPORT_output_2015_06_01__00_19_42
      I prefer the function strftime in POSIX for formatting dates. The only downside is that documentation for the format codes is "borrowed" from "C" and not included in perl's documentation.
      use strict; use warnings; use POSIX 'strftime'; my $outfolder = strftime "Report_Output_%Y_%m_%d__%H_%M_%S", localtime(); print $outfolder;
      Bill

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1128498]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-19 15:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found