claf
claf

Reputation: 9263

How do I format dates in Perl?

I'm modifying a pre-existing script in Xcode to customize my file headers. The script is Perl and it's not my best langage. :)

I just need to insert the current date in the header in dd/mm/yy format.

Here is my script :

#! /usr/bin/perl -w
# Insert HeaderDoc comment for a header
#
# Inserts a template HeaderDoc comment for the header.
use strict;

# get path to document
my $headerPath = <<'HEADERPATH';
%%%{PBXFilePath}%%%
HEADERPATH
chomp $headerPath;
my $rootFileName = &rootFileNameFromPath($headerPath);

print "/*";
print " * $rootFileName\n";
print " * Project\n";
print " *\n";
print " * Created by Me on ";
# in bash it would be something like that :
# date +%d/%m/%y | awk '{printf "%s\n", $1}';
print " * Copyright 2009 My_companie. All rights reserved.\n";
print " *\n";
print " */\n";

sub rootFileNameFromPath {
    my $path = shift;

    my @pathParts = split (m'/', $path);
    my $filename = pop (@pathParts);
    my $rootFileName = "$filename";
    $rootFileName =~ s/\.h$//;
    return $rootFileName;
}

exit 0;

I've just modified the print command so don't ask me for the rest of the code :)

Upvotes: 6

Views: 16228

Answers (3)

Telemachus
Telemachus

Reputation: 19725

Rather than removing strict (!), why not just make the code strict clean?

my ($mday, $mon, $year) = (localtime(time))[3, 4, 5];

$mon  += 1;
$year += 1900;

printf "%02d/%02d/%02d\n", $mday, $mon, $year % 100;

Maybe even better (since more familiar looking to someone who asked in terms of Bash):

# At the top, under use strict;
use POSIX qw/strftime/;

# then later...
my $date = strftime "%d/%m/%y", localtime;
print "$date\n";

Funny coincidence: Perl Training Australia publishes semi-regular tips (you can get them via email or online), and just today there's a new one on strftime.

Upvotes: 19

Dave Rolsky
Dave Rolsky

Reputation: 4532

You could also use DateTime and related modules, which is of course complete overkill for a little script like this. But for a larger app, you should use solid modules rather than doing everything the long way. For the record, with DateTime you'd write:

DateTime->today()->strftime('%d/%m/%y');

Or you could use the more modern CLDR format language:

DateTime->today->format_cldr('dd/MM/YYYY');

Upvotes: 9

Anand
Anand

Reputation: 7764

@time = localtime(time);
$mday = $time[3];
$mon = $time[4]+1;
$year = $time[5]+1900;
print "$mday/$mon/$year\n";

Should do it.

Edit:

printf "%02d/%02d/%4d",$mday,$mon+1,$year+1900";

Will take care of the padding with zeroes too.

Upvotes: 2

Related Questions