in reply to Re: Translating ANSI C to Perl
in thread Translating ANSI C to Perl

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

Replies are listed 'Best First'.
Re^3: Translating ANSI C to Perl
by bart (Canon) on Dec 04, 2006 at 12:25 UTC
    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;
      Bart,

      Now, almost everything is working :-) but I see a little difference between C code and Perl, do you help me to understand why ?

      ANSI C:
      $ sudo ./get_HW_KEY e000f030392f30322f303400fc00
      Perl:
      $ sudo perl seek.pl e000f030392f30322f303400fcc4
      best regards
        The bug is in your C code. fgets() stops after reading 13 characters and puts a NULL character into position 14, in order to ensure that your string is always properly NULL terminated. Your perl code reads all 14 characters from the file.


        TGI says moo