Re: 142 (v1): Enhanced Pack/Unpack

[email protected] (Tom Christiansen)
Newsgroups perl.perl6.language.data
Message-ID <21279.967140762@chthon>
Here was my old demo/proposal, such as it was.

--tom

    $buff = "\0" x rusage->sizeof();
    syscall(&SYS_getrusage, &RUSAGE_SELF, $buff)      && die "getrusage: $!";

    $ru = rusage->new_from_buffer($buff);
# or
    $ru = rusage->new();
    $ru->unpack($buff);
# or 
    @fields = rusage->unpack($buff);
# or 
    @fields = unpack(rusage->typedef, $buff);
# or 
    $ru = rusage->read(*FH);
# or
    read(FH, $buff, $rusage->sizeof);
    $ru = rusage->new_from_buffer($buff);
# or
    read(FH, $buff, $rusage->sizeof);
    @fields = unpack(rusage->typedef, $buff);

Class methods:

    $obj = CSTRUCT->new();	    # construct empty
    $obj = CSTRUCT->unpack($buff);  # construct from packed buffer

    $obj = CSTRUCT->new(	    # construct from pairs
	FIELD1 => "value", 
	FIELD2 => "value", 
    );

    $obj = CSTRUCT->read(*FH);	    # construct from next bytes on stream
    CSTRUCT->seek(*FH,10);		# goto record 10 on stream of CSTRUCTs

    $recsize   = CSTRUCT->sizeof(); # bytes in packed record
    $pack_mask = CSTRUCT->typedef(); # format for pack/unpack

Object methods:

    $x = $obj->field;		# get
    $obj->field($value);	# set

    $obj->unpack($buff);	
    print $obj->pack;	

    $obj->write(*FH);		# write packed $obj to stream
    $obj->read(*FH);		# read packed object from stream
    $obj->seek(*FH,10);		# goto record 10 on stream of (ref $obj)

    print $obj->as_string;
    print $obj->as_hash;

Example using wtmp log file:

1) Show record of user id #178

    use utmp;  # would have been #include <utmp.h>

    open(WTMP, "/usr/adm/wtmp");

    utmp->seek(*WTMP, 178);
    $him = utmp->read(*WTMP);

    printf "uid %d logged on from %s on %s.\n",
	$him->ut_uid, $him->ut_host, scalar local $him->ut_date;

2) Paul's updating records in place
    
    use employee;
    open(FH, "+< /tmp/empdata");
    $obj = employee->new();
    while ($obj = $obj->read(*FH)) {
	$obj->salary($obj->salary * 1.06); # *= 1.06
	seek(FH, 0, 1);
	$obj->write(*FH);
    }
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.