-3

I need to write an union function using Perl, and what I did is here, questions is followed by code.

sub union
{
    my @array1  = qw/a b c d/;
    my @array2  = qw/a f g h/;
    my %myunion = ();
    @myunion{ @array1, @array2 } = (1) x ( @array1 + @array2 );
    @myunion = keys %myunion;
    return @myunion;

    #if(){
    #    return @myunion;
    #}
    #else{
    #    return join ',', @myunion;
    #}
}
my @uString = union( [ 1, 2, 3 ], [ 2, 3, 4 ] );
my @uList   = union( [ 1, 2, 3 ], [ 2, 3, 4 ] );
print "$uString\n" 
print "@uList\n";

So without my command part, my out put is a b c d f g h in random order, but I want to make them as 1 2 3 4 in random order as what I write as input in my @uList. Also I need to check whether the caller requires a list, if it is it will return 1 2 3 4in random order, otherwise, it will return a comman-seperate string of the union which should be 1,2,3,4 in random order. So I want to know what should I do in the condition part of the if else statement.

PerlDuck
  • 5,610
  • 3
  • 20
  • 39
nicken
  • 43
  • 2

1 Answers1

2

Use the @_ variable to retrieve subroutine parameters.

To create the hash keys, you can let the values undefined.

#! /usr/bin/perl
use warnings;
use strict;

sub union {
    my ($aref1, $aref2) = @_;
    my %union;
    @union{ @$aref1, @$aref2 } = ();
    return keys %union
}

my @union = union([1, 2, 3], [2, 3, 4]);
print "@union\n";

or

my $union = join ',', union([1, 2, 3], [2, 3, 4]);
print "$union\n";
ikegami
  • 367,544
  • 15
  • 269
  • 518
choroba
  • 231,213
  • 25
  • 204
  • 289
  • so what if I call $uString and @uList, it will show different answer, as I mentioned before, if I call uString it will show 1,2,3,4 if I call uList it will show 1 2 3 4, one with comma, one not – nicken Dec 09 '17 at 20:39
  • @nicken, I made a change to the answer that shows how you can get `1,2,3,4` when that's what you want. – ikegami Dec 09 '17 at 20:47
  • @ikegami I know that way, but what if I call my $uString = union([1,2,3],[2,3,4]); then it will reaturn 1,2,3,4 ,so I think I need if else statement to chck whther it call is string or list. – nicken Dec 09 '17 at 20:58
  • @nicken: When I do `$uString = union(...)`, I'm getting the number of elements back, not `1,2,3,4`. That's what [keys](http://p3rl.org/keys) returns in scalar context. – choroba Dec 09 '17 at 21:16
  • @choroba, The OP asking how to write `union` so its result is based on context. – ikegami Dec 09 '17 at 21:44
  • @nicken, The bit you are missing is `wantarray`, but it's a bad idea to use it here. Finding the union of sets and formatting numbers for output are two unrelated tasks. Consult the answer to see how you can get `1,2,3,4` when that's what you want.1 – ikegami Dec 09 '17 at 21:46