MadisonCooper
MadisonCooper

Reputation: 236

How can I use an array slice to access several elements of an array simultaneously?

I'm trying to modify this script:

#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
use Math::Vector::Real;
use constant DEG_PER_RAD => 45 / atan2(1, 1);

my ( $source, $out ) = qw/ OUT4 OUTABA12 /;

open my $in_fh,  '<', $source or die qq{Unable to open "$source" for input: $!\n};
open my $out_fh, '>', $out    or die qq{Unable to open "$out" for output: $!\n};


my @data;
push @data, V(split) while <$in_fh>;
my @aoa;

for my $i ( 0 .. $#data ) {
    for my $j ( 0 .. $#data ) {
        my $val1 = $data[$i];
        my $val2 = $data[$j];

        if ($val1 != $val2) {

            my $math = sqrt(($val1->[0] - $val2->[0])**2 +
                ($val1->[1] - $val2->[1])**2 +
                ($val1->[2] - $val2->[2])**2);

                if ($math < 2.2) {
                    push @aoa, "@$val1 @$val2";
                    }
        }
    }
}

for my $k ( 0 .. $#aoa ) {
    for my $m ( 0 .. $#aoa ) {

        my $aoadata1 = $aoa[$k];
        my $aoadata2 = $aoa[$m];

        my $vect1 = $aoadata1[0..2];
        my $vect2 = $aoadata2[0..2];

        print "$vect1 $vect2\n";    

    }
}

.

At the end of the script, I want to be able to do things with the variables $aoadata1 and $aoadata2 in fields 0-2. However, I cannot get them to stop throwing up errors regarding things not referenced right (I think). Can anyone tell me why this is happening/how to fix it?

Thanks.

Upvotes: 0

Views: 76

Answers (1)

choroba
choroba

Reputation: 241858

If you want to use multiple subscripts in an array, you have to change the sigil:

@array[ 0 .. 2 ];
@{ $arra_ref }[ 0 .. 2 ];

It makes no sense to assign the result to a scalar, though. Use an anonymous array:

my $aoadata1 = $aoa[$k];
my $vect1 = [ @{ $aoadata1 }[ 0 .. 2 ] ];

or, without the temp var:

my $vect1 = [ @{ $aoa[$k] }[ 0 .. 2 ] ];

It might still not work, as I noticed you used

push @aoa, "@$val1 @$val2";

Did you mean

push @aoa, [ @$val1, @$val2 ];

or something similar?

Upvotes: 5

Related Questions