otaviof has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I need to "translate" the ANSI C code below to Perl, but I have some hard times in seek function ... can you help me ?
char *getDevMemSTR (void) { FILE *fh; unsigned char read[32]; char *key; int n = 0; key = (char *) malloc(20 * sizeof(char)); fh = fopen("/dev/mem", "r"); fseek(fh, 0xFFFF2, SEEK_SET); fgets(read, 14, fh); for (n = 0; n < 14; n++) { sprintf(key, "%s%2.2x", key, read[n]); } return key; }
Thank you indeed !

Replies are listed 'Best First'.
Re: Translating ANSI C to Perl
by davorg (Chancellor) on Dec 04, 2006 at 10:57 UTC

    What problems are you finding with the seek function? It looks to me as tho' Perl's seek function is very similar to the one in C. The SEEK_* constants are defined in Fcntl.pm.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      Hello Dave,

      I made successfully seek routine, and almost convert this code, but my problems now are in "sprintf", take a little look in my (newbie) perl code:
      #!/usr/bin/perl -w use warnings; use Fcntl qw(:seek); my $key = ""; my $read = ""; my @list; # getting value from /dev/mem open(MEM, "< /dev/mem") or die "Error while opening /dev/mem"; seek(MEM, 0xFFFF2, SEEK_SET); sysread(MEM, $read, 14); close(MEM); @list = split('', $read); foreach (@list) { $key = sprintf("%s%2.2x", $key, $_); print $key, "\n"; }
      and:
      $ sudo perl seek.pl Argument "à" isn't numeric in sprintf at seek.pl line 20. 00 Argument "\0" isn't numeric in sprintf at seek.pl line 20. 0000 Argument "ð" isn't numeric in sprintf at seek.pl line 20. 000000 00000000 0000000009 Argument "/" isn't numeric in sprintf at seek.pl line 20. 000000000900 00000000090000 0000000009000002 Argument "/" isn't numeric in sprintf at seek.pl line 20. 000000000900000200 00000000090000020000 0000000009000002000004 Argument "\0" isn't numeric in sprintf at seek.pl line 20. 000000000900000200000400 Argument "ü" isn't numeric in sprintf at seek.pl line 20. 00000000090000020000040000 Argument "Ä" isn't numeric in sprintf at seek.pl line 20. 0000000009000002000004000000
      Should I use pack function or something like ?

      thank's
        Nah, your problem is not in the seek, but it is here:
        @list = split('', $read); foreach (@list) { $key = sprintf("%s%2.2x", $key, $_); print $key, "\n"; }
        In Perl, characters are not numbers, but single character strings. Instead of @list = split('', $read); you can do
        @list = unpack 'C*', $read;
        and proceed as you did; or rewrite the loop, for example like this:
        @list = split('', $read); $key = join "", map { sprintf "%2.2x", ord } @list;
        Or rewrite both, to a blend of the two:
        @list = unpack 'C*', $read; $key = join "", map { sprintf "%2.2x", $_ } @list;