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

Hello again,

I'am using code similar to the following:

#!/perl/bin/perl.exe -w use strict; my @data = ( ["1040564312", "IN", 258381720], ["1040564312", "OUT", 4194077715 ], ["1040564322", "IN", 258385268], ["1040564322", "OUT", 4194081727], ); foreach my $record (@data) { for my $i (0 .. 2) { print $record->[$i] . " "; } print "\n"; }
It produces the following output
1040564312 IN 258381720 1040564312 OUT 4194077715 1040564322 IN 258385268 1040564322 OUT 4194081727
What I need it to do is calculate the difference of element 0 from itmes 1 and 2 (i.e. 1040564312 - 1040564312 = 0), and then print the IN value followed by the OUT value so the output should be:
0 258381720 4194077715 0 258385268 4194081727

Any suggestions?

update (broquaint): title change (was Array)

Replies are listed 'Best First'.
Re: Array
by fruiture (Curate) on Nov 27, 2002 at 19:10 UTC

    I'd say your data structure is not ideal, it's surely much more usefull to improve the structure than the program working on it.

    while( @data > 1 ){ my $i = shift @data; my $o = shift @data; printf "%d %d %d\n", $i->[0] - $o->[0], $i->[2] , $o->[2]; }

    This will clobber your array.

    update: sorry, PRE=>CODE

    --
    http://fruiture.de
      Do you know why your routine is returning this data:
      0 258381720 -100889581 0 258385268 -100885569
      instead of:
      0 258381720 4194077715 0 258385268 4194081727
      Thanks in advance

        Because 4194081727 needs 32 Bit to be stored correctly as number. Looks like the '%d' template wants a smaller int. Using '%s' will help.

        --
        http://fruiture.de
Joining records from a file(was Re: Array)
by demerphq (Chancellor) on Nov 27, 2002 at 20:41 UTC
    Hi,

    fruiture showed you a solution that works just fine on your posted data set. (++) But it seems worth pointing out that it wouldn't work if the records werent paired like that. For instance on

    my @data = ( ["1040564312", "IN", 258381720], ["1040564322", "IN", 258385268], ["1040564322", "OUT", 4194081727], ["1040564312", "OUT", 4194077715 ], );
    In the future can you please think of a better title name than "array". :-) And maybe try to descibe your problem a bit more?

    --- demerphq
    my friends call me, usually because I'm late....