#!/usr/bin/perl
use warnings;
use diagnostics;
use strict;

# backticks.pl
#
# Please send corrections, suggestions for improvement, comments etc. to
# chandra@ee.uwa.edu.au
#
# The purpose of this script is to illustrate how to extract output from
# shell builtins or system commands from within a Perl script
# so as to assemble the variables to create a directory named
# username-mmm-yyyy
# where 
# username is the user's login name
# mmm is the three-letter abbreviation for the month
# yyyy is the four-digit year

my ($date, $month, $year, $month_year, @export, $export, $user, $dir);

# On my system, the locale defines the default format for date
# and typical output is 
# Wed Jan 16 16:07:52 WST 2008
$date = `date`;
$date =~ m/\w{3}\s(\w{3}).*(\d{4})$/; # do not forget the ~
$month = $1;
$year = $2;
print "$month-$year\n";

# Alternatively, one could define the format to suit
$month_year = qx\date +%b-%Y\;
chomp $month_year; # chomp because this string is newline terminated
print "$month_year\n";

# export is a shell builtin whose syntax is displayed by typing
# help export
# on the command line in a terminal
# A typical output after grepping the output of
# sh -c export -p
# is
# export USER='username'
#
# @export = `export -p`; # does not work for a shell builtin
@export = `sh -c export -p`;
($user) = grep /USER/, @export; # use list mode for assignment
$user =~ m/.*\W+(\w+)\W+$/;
$user = $1;
print "$user\n";

$dir = $user."-".$month."-".$year;
print "$dir\n";

# create desired directory within home directory 
# without error checking of any kind
# uncomment to execute if desired
# chdir; # go to home directory
# mkdir $dir; # create directory, assuming it does not exist