in reply to Translating ANSI C to Perl

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

Replies are listed 'Best First'.
Re^2: Translating ANSI C to Perl
by otaviof (Acolyte) on Dec 04, 2006 at 12:03 UTC
    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;
        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