Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Medicine monthly prices by dose calculator

by chanio (Priest)
on Oct 23, 2005 at 01:59 UTC ( #502271=CUFP: print w/ replies, xml ) Need Help??

Someone may be in need of taking some medicine during a long time.

Since every product comes in different quantities, you might need to reckon the monthly price that you would have to pay for taking such medicines. But not only does it depend on the products but also in the way that you might be consuming them. So, just try this one-liner to know how expensive is your recovery.

You need to first, write a text file with the required data for each product. Each line should have the name of the medicine, then a tab character, then the number of units of consumption that the product has (that is, 30 pills/tablets/doses/drinks/etc., and finally another tab character with its price.

Then, the one-liner reads that file and keeps asking the number of units that you consume each day of a 31 days month (the worse of the cases). Array @precio (@prices in English) holds each line of your file. Scalar $acumes ($monthacum in English) should keep on summing the final ammount. Every element of the @precio array is split by \t (tab char) into the three original values. Those would be used to ask for the daily dose, and to deduct the price per dose and each monthly cost.

These partials would be displayed as well as summed up. Then finally, the total ammount should be displayed between two lines of equal signs.

Do you like it? These days, I find it very useful :( .

(update: now, here, apples are a bit expensive... that's why I am sick! :) )

>cat medicines.txt Powder-A 400 gr. 30 70.18 Liquid-A D20 30 33.83 Atomizer 25 mg 56 12.60 Apples 50 63.65

>perl -e"my @precio;open PR,'medicines.txt';@precio=<PR>;close PR;chom +p(@precio);print(\"\n** MEDICINE PRICES BY DOSES PER MONTH **\n\n\"); +my $acumes;foreach my $li (@precio){next if ($li=~/^[_#\W]/);my ($med +,$uni,$pre)=split(/\t/,$li);my $dos;print('Daily dose of ',$med,'? => +');$dos=<>;$dos=~s/[^\d\.]//g;my $tot=sprintf(\"%6.2f\",$pre/$uni*$do +s*31);print(' Costs.................',\" \t\t\t$tot \$\/month.\n\"); +$acumes+=$tot;}my $lit=\"\nTotal to spend with medicines every month: + $acumes \$\n\";print('=' x length($lit),$lit, '=' x length($lit +),\"\n\");"

The output:

** MEDICINE PRICES BY DOSES PER MONTH ** Daily dose of Powder-A 400 gr. ? =>1 Costs................. 72.52 $/month. Daily dose of Liquid-A D20 ? =>0.5 Costs................. 17.48 $/month. Daily dose of Atomizer 25 mg ? =>1 Costs................. 6.98 $/month. Daily dose of Apples ? =>2 Costs................. 78.93 $/month. ========================================================== Total to spend with medicines every month: 175.91 $ ==========================================================

Edited by GrandFather to change medicine names

Update with date of renewal of every medicine + better formating (LINUX users)

Final Output

** MEDICINE PRICES BY DOSES PER MONTH (21-January-2006)** Daily dose of Powder-A 400 gr. (1.. 30)? =>1 Costs................. 72.52$/month [Buy Next:20-Februar +y-2006 ] Daily dose of Liquid-A D20 (1.. 30)? =>3 Costs................. 104.87$/month [Buy Next:31-January +-2006 ] Daily dose of Atomizer 25 mg (1.. 56)? =>1 Costs................. 6.98$/month [Buy Next:18-March-2 +006 ] Daily dose of Apples (1.. 50)? =>10 Costs................. 394.63$/month [Buy Next:26-January +-2006 ] ============================================ |Medicine Monthly Total 2 spend : 579.00$ | ============================================

1) A text file with fields separated by '|' chars

cat <<EOF >medicines.txt ## PRODUCT |NUM.DOSES|PRICE ##--------------+---------+----- Powder-A 400 gr.|30|70.18 Liquid-A D20|30|33.83 Atomizer 25 mg|56|12.60 Apples|50|63.65 EOF

2) Perl one-liner commented

perl -MPOSIX -e' my ($tnow,$gday)=(time,int(60*60*24)); ## MANUAL WAY OF FINDING FUTURE + DATES my (@precio); ## GETTING THE DATA TO PROCESS open MED,"medicines.txt" or die("file does not open...$!"); @precio=(<MED>); close MED; chomp(@precio); ## PRINTING HEADING WITH TODAY'S + DATE print("\n** MEDICINE PRICES BY DOSES PER MONTH (".strftime("%d-%B-%Y", +localtime).")**\n\n"); my ($acumes); foreach my $li (@precio) ## ASKING FOR DAILY DOSES AND PR +INTING PARTIALS AND DATES { next if ($li=~/^[_#\W]/); ## SKIP COMMENTS my ($med,$uni,$pre)=split(/\|/,$li); ## GET FIELDS: PRODUCT,UNITS,PRI +CE my $dos; printf("Daily dose of %-40s (1..%3i)? =>",$med,$uni);## GET DAILY DO +SE $dos=<STDIN>; $dos=~s/[^\d\.]//g; ## CLEAN INPUT my $tot=sprintf("%6.2f",$pre/$uni*$dos*31);## PARTIAL CONSIDERING 31 +DAYS IN A MONTH printf(" Costs................. \t %9.2f\$/month [Buy Next:%-18s]$/" +,$tot,strftime("%d-%B-%Y",localtime($tnow+int($uni/$dos*$gday))));## +PARTIAL RESULT $acumes+=$tot } my $lit=sprintf("\n\|Medicine Monthly Total 2 spend :%9.2f\$\ |$/", $ +acumes); print(" ","=" x (length($lit)-4),$lit," ", "=" x (length($lit)-4),"\n" +);## PRINTING TOTAL '

Comment on Medicine monthly prices by dose calculator
Select or Download Code
Re: Medicine monthly prices by dose calculator
by QM (Vicar) on Oct 23, 2005 at 17:34 UTC
    If you want others to make use of this, try formatting it as a program file instead of a one liner. Also, I'd suggest changing print to printf almost everywhere (be consistent, unless printf is overkill).

    Using open without checking for errors is asking for trouble. If you were going to do a one liner, why not use the -n option in perlrun? For a script as small as this, pass the input file on the command line, and use the while (<>) magic.

    Many medications come in different concentrations, so comparing pill counts is still misleading. Why not expand your thinking a bit and give 2 sets of inputs, one the presribed daily dosage in standard units (say milligrams of active ingredient), and the other input listing the packaging choices available? Then the script can output the list of most economical choices (assuming that all are equally safe and effective, of course).

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      Thank you QM for your suggestions. They are now, listed for others to consider them...

      About passing the input file on the command line, it would be an interesting issue since I would then need to use the <STDIN> diamond to ask for the quantities. If not, it would mess with the previous <> input ...

      I wouldn't ever change the medicine's standard units, since they are not part of the script. (They are part of life's script and are only restricted to the doctors that prescribed them: it is not the same to build a house with one mason during 30 days or building it with 30 masons in one day)

      It is a one-liner, because I wouldn't bother filing it as another script. But it is useful. I'll consider the -n option, promised!

        It is a one-liner, because I wouldn't bother filing it as another script.
        I don't know what system you're using, but most systems I know of would allow you to run the script directly, without invoking perl first. One of the more difficult ones to figure out on your own is Windoze -- you need help from ASSOC and FTYPE:

        ####################################

        ####################################

        Here's your code reformatted:

        About passing the input file on the command line, it would be an interesting issue since I would then need to use the <STDIN> diamond to ask for the quantities. If not, it would mess with the previous <> input ...
        Perhaps you just need to experiment more! Put the following in a file, and pass a text file on the command line:
        #!/your/perl/here use strict; use warnings; while (<>) { print "one: $_"; } print "\n\n: now reading from STDIN: \n\n"; print "Enter data: "; while (<>) { print "two: $_"; print "Enter data: "; }
        I think you missed my point about quantities, etc. If the doctor prescribes 2 pills per dose, 5 times/day, containing 200mg of pleonasm, and you can buy 200mg pills for 10 cents each, then it costs you $1.00/day. But if you can get 400mg pills for 15 cents each, it only costs 75 cents/day.

        I'm suggesting that some medications come in different pill concentrations, and you might save money by shopping around. And you might program that by using a file for the prescribed doses, and another file for the concentration/price tables.

        Now, I've left something out. You could do this by passing 2 files on the command line, and making judicious use of the continue and eof elements. Just check out eof for more details.

        Cheers,

        -QM
        --
        Quantum Mechanics: The dreams stuff is made of

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://502271]
Approved by planetscape
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2014-08-22 02:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (145 votes), past polls