Blob


1 #!/usr/bin/perl
3 # Write a program that prints today's date and the day of the week, but
4 # allows the user to choose to send the output to a file, a scalar, or both
5 # at the same time. No matter which one the user selects, send the output
6 # with a single print statement. If the user chooses to send the output to
7 # a scalar, at the end of the program print the scalar's value to standard
8 # output.
10 use v5.24;
11 use warnings;
12 use strict;
13 use utf8;
14 use local::lib;
16 use Getopt::Std;
17 use IO::Tee;
19 my %opts;
20 getopts('sf:', \%opts);
21 my $fh;
22 my $string_ref;
23 if (!%opts) {
24 die "Usage: $0 [-s] [-f file]";
25 }
26 if ($opts{s} && $opts{f}) {
27 open my $sh, '>', \$string_ref;
28 open my $th, '>', $opts{f} or die "Unable to open '$opts{f}': $!";
29 $fh = IO::Tee->new($sh, $th);
30 } elsif ($opts{s}) {
31 open $fh, '>', \$string_ref;
32 } elsif ($opts{f}) {
33 open $fh, '>', $opts{f} or die "Unable to open '$opts{f}': $!";
34 }
35 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
36 my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
37 my @days = qw(Sun Mon Tue Wed Thu Fri Sat);
39 printf {$fh} ("%s %s %s %02d:%02d:%02d %4d",$days[$wday],$months[$mon],$mday,$hour,$min,$sec,$year+1900);
41 if ($opts{s}) {
42 open my $sh, '<', \$string_ref;
43 my $str = <$sh>;
44 printf("Scalar: %s\n", $str);
45 }