I have a Perl program I am editing. The idea is to have it write a record to another file whenever a user access this program. Here is the Perl code I am using:

open(MYFILE, ">>/usage.file");
print MYFILE "USERID: `whoami` used this on DATE: `date` \n";
close MYFILE;

the problem is that the UNIX commands (whoami and date) are not evaluated so it puts the exact string, as is, into the file.

How do I get the UNIX commands to be evaluated for userid and date?

thanks

You can't run commands inside of strings, well you can but its easier to just do it properly:

open(MYFILE, ">>/usage.file");
print MYFILE 'USERID: ', `whoami`, 'used this on DATE: ', `date`, "\n";
close MYFILE

if whoami and date return with a newline then the above line will be broken up into two or three lines. You may want to do something like this instead:

my $who = `whoami`;
my $date = `date`;
chomp $whoami;
chomp $date;
open(MYFILE, ">>/usage.file") or die "$!";
print MYFILE "USERID: $whoami used this on DATE: $date\n";
close MYFILE

Of course the better solution is to use perl variables/functions for the date and whoami.

my $date = scalar localtime;
open(MYFILE, ">>/usage.file") or die "$!";
print MYFILE "USERID: $ENV{'USER'} used this on DATE: $date\n";
close MYFILE

I am assuming $ENV{'USER'} is the same information as whoami returns.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.