I was wondering how C makes certain things harder to write and perl (and similar languages) makes it easy to write.
As an example, consider the following problem: There is a file which contains two columns: first column contains fruit names and the second column contains prices. You are asked to write code to read them and store them in an array (or two arrays) so that given a name, you can find the price. It looks simple, right? How would you write it in C if you are also told that your code should be able to handle any number of items! In Perl you would write like this
#!/usr/local/bin/perl use strict; my %items; open (FD, "data" ) || die "unable to open file"; while (<FD>){ my @ar = split; $items{$ar[0]} = $ar[1]; } #here you can also get the name from the user and print the #price. print "price of apple is : ", $items{"apple"}, "\n";
This code will work regardless of number of items in the file!
Enjoy!In reply to C vs. Perl by podian
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |