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!
podian

In reply to C vs. Perl by podian

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.