Okay. Here's a somewhat complete though simplistic implementation of the program written in C. It is more complete, in that it includes the code for prompting the user and retrieving the input, and makes some attempt at error checking (not enough), that was completely absent from the perl version above. It also cheats by using a linear search rather than hashing the lookup.

#include <stdio.h> #include <stdlib.h> #include <sys\stat.h> #include <string.h> #include <fcntl.h> #include<io.h> #define FILE "data" #define LINESIZE 80 int main( ) { struct stat statbuf; char *linebuf, *p, *found; int fh, price; if( ! stat( FILE, &statbuf ) && ( p = calloc( statbuf.st_size, sizeof( char ) ) ) && ( fh = open( FILE, O_RDONLY|O_BINARY, S_IREAD ) ) && ( read( fh, p, statbuf.st_size ) > 0 ) && ! close( fh ) ) { printf( "%s", "Fruit? " ); linebuf = calloc( LINESIZE, sizeof( char ) ); fgets( linebuf, LINESIZE, stdin ); *( linebuf + strlen( linebuf ) -1 ) = 0; if( (found = strstr( p, linebuf )) ) { sscanf( found + strlen( linebuf ), "%i", &price ); printf( "%s costs %d", linebuf, price ); } else { printf( "No price for %s available\n", linebuf ); } free( p ); free( linebuf ); } else { printf( "Error: %d", errno ); } return (0); }

This is about as simple as it is possible to do write something roughly equivalent in C, whereas I've no doubt that this coudl be done as a perl one-liner with a little effort.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Hooray!


In reply to Re: Re: Re: Re: C vs. Perl by BrowserUk
in thread 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.