How do I format dates in Perl?

I am modifying a pre-existing script in Xcode to customize the file headers. The script is Perl, and it is not my best language. :)

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

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 just changed the print command, so don't ask me about the rest of the code :)

+6
date perl templates
source share
3 answers

Instead of removing strict (!), Why not just make strict code 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 (as a more familiar one, looking at 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"; 

A funny coincidence: Perl Training Australia publishes semi-regular tips (you can get them by email or online), and only today is new at strftime .

+19
source share

You can also use DateTime and its related modules, which of course means full overflow for a small script like this. But for a larger application, you should use solid modules, and not do all the long way. To record with DateTime you must write:

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

Or you can use a more modern language of the CLDR format:

 DateTime->today->format_cldr('dd/MM/YYYY'); 
+9
source share
 @time = localtime(time); $mday = $time[3]; $mon = $time[4]+1; $year = $time[5]+1900; print "$mday/$mon/$year\n"; 

Must do it.

Edit:

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

Take care of padding with zeros too.

+2
source share

All Articles