in reply to Re: How to combine these 2 subroutines in one?
in thread How to combine these 2 subroutines in one?

Thanks to both of you!
I have tried this,which works if I pass the array as array, but why can't I make it work if I pass the array as reference to array
sub clean_list { my $type_of_arg=ref(\@_); my @array_with_duplicates=(@_); my @array_no_duplicates; if($type_of_arg eq 'ARRAY') #if the list is passed as an ar +ray { my $previous = ''; while (scalar @array_with_duplicates > 0) { my $next = shift(@array_with_duplicates); if ($previous ne $next) { push(@array_no_duplicates, $next); $previous = $next; } } } elsif($type_of_arg eq 'REF') #if the list is passed as a refere +nce to an array { my %hash; @hash{@{$_[0]}}=(); #@{$_[0]}=keys %hash; @array_no_duplicates=keys %hash; } return (@array_no_duplicates); } open(IN, '<', 'ex5.acc') or die "Could not read file\n"; my @initial_array = <IN>; close IN; @initial_array = sort @initial_array; my @final_array = clean_list(@initial_array); #this works # @final_array = clean_list(\@initial_array); #this does not work # Save the clean table open(OUT, ">", "ex5.acc.CLEAN") or die "Could not create file\n"; print OUT @final_array; close OUT;

Replies are listed 'Best First'.
Re^3: How to combine these 2 subroutines in one?
by Athanasius (Archbishop) on Apr 03, 2014 at 13:45 UTC

    Two obvious problems (there may be others):

    • @_ is the array of arguments passed into the subroutine, so \@_ will always be an array reference. You need ref($_[0]) which tests the first argument (but see my answer above as to why this may not be the best approach).

    • If the array is passed in as a reference, $type_of_arg will be the string 'ARRAY', indicating an array reference. If the array is passed in as a list (and if the first element of that list doesn’t happen to be a reference), $type_of_arg will be the empty string, not 'REF'. Again, see ref.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Aha, I see, will look further in my code, thank you for the tips :)
        Ok, I tried this
        sub clean_list { my $type_of_arg=ref(@{ $_[0] }); print "Type of argument passed is: $type_of_arg\n"; } open(IN, '<', 'ex5.acc') or die "Could not read file\n"; my @initial_array = <IN>; close IN; clean_list(@initial_array); clean_list(\@initial_array);

        and, if I pass the list as a reference it works OK, whereas, if I pass it as a simple array I get:
        Can't use string ("L13923") as an ARRAY ref while "strict refs" in use + at Lesson10.pl line 32.
        The L13923 is the first id that I have in my input file...