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

Hello Monks, Can anyone tell me how to read and write directly to a given memory location in perl. This is quite trivial in Pascal (from my youth...Ahh) you just create a pointer and directly assign the address to it. It then points to whatever data is at that address thus giving you the power to totally screw up your system. I need to work with a memory mapped device directly and it would be nice to use perl if at all possible and screw up my system the modern way. Any ideas ? Thanks, your help is as always highly appreciated ...

Replies are listed 'Best First'.
Re: Memory addressing
by Tanktalus (Canon) on Nov 25, 2005 at 05:23 UTC

    What operating system are you attempting this on? Pretty much all modern OS's won't let you do this. Even in Pascal anymore.

    The way to do this is via a device driver that sits in an elevated-privilege space (e.g., the kernel), and communicate with the driver instead.

      win2k server or pro

        No chance unless you wish to write a kernel mode driver that does that sort of stuff and talk to that from Perl. Once you've written the driver the talking to it is easy.


        DWIM is Perl's answer to Gödel
Re: Memory addressing
by spiritway (Vicar) on Nov 25, 2005 at 08:17 UTC

    You can get the memory location of a variable by doing something like this:

    use strict; use warnings; my @var=(1,2,3); my $var_ref=\@var; print "$var_ref\n"; print 0+$var_ref . "\n";

    This would give you output looking something like this:

    ARRAY(0x182f26c) 25358956

    I don't know of any way to write directly to a memory location. In fact, AFAIK, the actual hardware protects against such actions by generating (I think) a segmentation fault. I think you'd have to get down to the bare metal to do this. I agree, it's fun to trash your system, but they keep making it harder. Unless, of course, you use Windows.

Re: Memory addressing
by Perl Mouse (Chaplain) on Nov 25, 2005 at 09:42 UTC
    Untested:
    $ sudo perl -we 'open my $mem, "+< /dev/mem"; seek $mem, 0xDEADBEEF, 0 +; print $mem "whatever" or die "Failed to write: $!"; close $mem';
    Perl --((8:>*
Re: Memory addressing
by fluffyvoidwarrior (Monk) on Nov 25, 2005 at 10:15 UTC
    Thanks everyone It looks like theres no trivial way to poke about with this problem. I'll have to try a different tack . . .
Re: Memory addressing
by Anonymous Monk on Nov 25, 2005 at 13:44 UTC