Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Array name with a Variable

by pc88mxer (Vicar)
on Apr 17, 2008 at 17:39 UTC ( #681254=note: print w/replies, xml ) Need Help??

in reply to Array name with a Variable

First I'd like to say that this is pretty clever:
foreach my $e (@array1, @array2) { $union{$e}++ && $intersect{$e}++ }
To solve your problem, just use an array of references to your set arrays:
my @sets = (\@array1, \@array2, ...); for my $i (0..$#sets) { for my $j ($i+1..$#sets) { compute_stuff($sets[$i], $sets[$j]); } }
Your union/intersection code will now look like:
sub union_intersection { my ($set1, $set2) = @_; my (%union, %intersection) for my $e (@$set1, @$set2) { ... } ... }

Replies are listed 'Best First'.
Re^2: Array name with a Variable
by godevars (Initiate) on Apr 17, 2008 at 20:29 UTC
    I tired this first and am running into an error. I am very new at Perl so may be missing how the subroutine is set up. I run my script witht he following (my actual arrays have many more words than that in my sample):
    my @sets = (\@array1, \@array2, \@array3, \@array4 ); for my $h (0..$#sets) { for my $j ($h+1..$#sets) { compute_stuff($sets[$h], $sets[$j]); } } Sub union_intersection { my ($set1, $set2) = @_; my (%union, %intersect); foreach my $e (@$set1, @$set2) { $union{$e}++ && $intersect{$e}++ } my @intersect = sort keys %intersect; #print FILEOUT "@intersect\n"; print FILEOUT scalar @intersect; print FILEOUT "\n"; }
    I get a syntax error on 2 lines. One on this line: my (%union, %intersect); The other near the last line (with '}'). Not sure why. In you example you did't have the semi-colon at the end and added it but that wasn't it. Also, don't I need to call the subroutine somewhere for it to work. Not sure if this an error on my part (e.g. not sure what compute_stuff should be doing). Thanks for the help-

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://681254]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (11)
As of 2018-03-20 20:30 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (259 votes). Check out past polls.