in reply to Can someone help me make this script more efficient
I shouldn't. I really shouldn't. ... Oh, what the heck. :)
#!/usr/bin/perl -w use strict; die "Usage: ", $0 =~ /([^\/]+)$/, " <[1|2|5|10|20|50]l | [5|10|20|50]p +> [...]\n" unless @ARGV; my $sum; for (@ARGV){ die "$_ is an invalid amount/type of currency!\n" unless /^(5|[125]0(?=p)|[125]0?(?=l))([pl])$/i; $sum += $1 / ${{ p => 100, l => 1 }}{lc $2}; } print "The total is L$sum.\n";
ben@Tyr:/tmp$ ./pocketful_of_rye 20l 5p 20P 50p 50L 10l 5l The total is L85.75.
The above is just a bit geek-snarky, but the point I would like to get across is that you'll want to rethink the structure of your program before you even start thinking about efficiency. Perl will execute it efficiently enough; you're not running millions of calculations per second anyway, or anything else where efficiency would matter. Even if this script took a full second to run, you wouldn't miss it. Program design, however, is critically important - not that it's specific to Perl in any way, but it's a critical aspect of any sort of programming that you'll ever do.
Even if your script is just homework - which I strongly suspect it is - there's no reason to not give it your best shot: this is where and how you learn to do the real thing. Before you ever put your hands to the keyboard, think - I mean really think - about the task at hand. Conciseness is good; so is clarity (one of the bits that makes the above program snarky is that I blithely stomped all over clarity in the interest of conciseness. :) Thinking about the operations you have to perform on the data and combining the common ones is also a reasonable approach (again, illustrated somewhat by the above despite the bit of Perl golf with the anonymous hash.)
Consider the user interface, too. Does it make sense to interrogate the user about every single possibility, as you do - or would it work better to let them specify the data in one shot, if at all possible? It seems to me that the range of what you're asking for is simple enough - the regular expression that I used covers everything you did in your script (the snarkiness there consists of requiring you, if you want to understand it, to run perldoc perlre and read it carefully.) This also allows you to validate the user data - always a good practice while coding.
I could go on for a bit, but I think you get the point. Think about the task; split it into chunks that are easily comprehensible (both mentally and in code); and write the code to handle those chunks. After ten or twenty years of doing this, start focusing on efficiency - if you're still concerned with it, that is.
Meanwhile, keep reading Perlmonks. There are lots of people here, many of them with good ideas and good coding habits. Stick around and learn - and remember to label your homework as such. It'll get you more help and less snarkiness. :)
-- Human history becomes more and more a race between education and catastrophe. -- HG Wells
|
|---|