date formatting in perl

my code:

$dateformat = yyyy_mm_dd
if($dateformat =~ m/yyyy/i)
{
print ("found");
$yyyy = strftime "%Y", localtime;
print ("year is $yyyy\n");
$dateformat =~ s/yyyy/$yyyy/;
print ("new date format is $dateformat\n");
}
elsif($dateformat =~ m/yy/i)
{
print ("found");
$yy = strftime "%y", localtime;
print ("year is $yy\n");
$dateformat =~ s/yy/$yy/;
print ("new date format is $dateformat\n");
}

output = 2011_mm_dd
Is there any method to do this in a simpler way or using sed? Please suggest

$dateformat = yyyy_mm_dd
if($dateformat =~ m/yyyy/i)
{
print ("found");
$yyyy = strftime "%Y", localtime;
print ("year is $yyyy\n");
$dateformat =~ s/yyyy/$yyyy/;
print ("new date format is $dateformat\n");
}
elsif($dateformat =~ m/yy/i)
{
print ("found");
$yy = strftime "%y", localtime;
print ("year is $yy\n");
$dateformat =~ s/yy/$yy/;
print ("new date format is $dateformat\n");
}

you are replacing the year only. you are replacing the month and date

replacing only the year.
eg: It ll either be "2011" or "11"

Not much simpler, just saves some duplicated code.

$dateformat = 'yyyy_mm_dd';
$fmt = ($dateformat =~ m/yyyy/i) ? '%Y' : $dateformat =~ m/yy/i ? '%y' : '';

if ($fmt ne '')
{
    print ("found");
    $year = strftime $fmt, localtime;
    print ("year is $year\n");
    $dateformat =~ s/$1/$year/;
    print ("new date format is $dateformat\n");
}

Thanks this works perfect :slight_smile:
can you explain the below syntax and how this works?

$fmt = ($dateformat =~ m/yyyy/i) ? '%Y' : $dateformat =~ m/yy/i ? '%y' : '';