As per my previous post, I thought it would be a good to try generating the filename of the output file based on the name of the source file. The tricky bit ended up being mostly easy, and the easy bit ended up being tricky. Unsurprisingly there’s a module devoted to splitting up filenames and thus, this resulted in my first use of a module as well:

use File::Basename;

followed by:

my $basename = basename($source, “.csv”);

the use of which in this instance, is based on the assumption that the source file is a .csv file (Comma Separated File). It takes the source name eg snailsource.csv and strips off the .csv. I create the new filename such:

$result = “$basename.txt”;

which results in snailsource.txt. it really was as simple as expressing the new name by adding “.txt” to the $basename variable. I suspect I could have called the “$basename” variable $snailsource or $filename etc.

What I hadn’t realised was that variables are “scoped” and are only recognised within the {} of your subroutine if they have not first been declared outside the subroutines. I eventually worked that out, through Perl Maven’s article. The hard bit was trying to understand why it still didn’t work. I spent an hour on Friday night getting nowhere then looked at it at the start of lunch today and had it solved in a couple of minutes.

Turns out that I’d been under the assumption that I needed to assign values to variables using “my” so the original version of the above line was:

my $result = “$basename.txt”;

within a {…} subroutine. I removed the “my” and it worked.

My little program now checks for 2 arguments, and if there is 2 arguments (source and output files), it sends the results to the specified output file. If there is only 1 argument (the source file), it generates the name of the output file using the name of the source file.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s