Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: A C-like brain in a Perl-like world

by runrig (Abbot)
on Sep 27, 2001 at 00:13 UTC ( [id://114929]=note: print w/replies, xml ) Need Help??


in reply to A C-like brain in a Perl-like world

sub merge { my (@array1,@array2) = @_;
This won't work. All arguments will go into @array1, and @array2 will be empty. You need to pass in array references if you want to preserve which argument is which (although the way your loop functions, it sort of doesn't matter). In fact, it looks like you are mixing up your array names with your scalar names in the merge function. Maybe you need to use strict and warnings??

Besides, the subroutine can be done more simply as:

sub merge { my %hash; @hash{@_} = (); sort keys %hash; } my @array1 = qw(a b c d e); my @array2 = qw(c d e f g); my @merged = merge(@array1, @array2); print "@merged\n";

Replies are listed 'Best First'.
Re^2: A C-like brain in a Perl-like world
by Aristotle (Chancellor) on Sep 27, 2001 at 13:30 UTC
    This is almost the approach I'd take; except to make it reference-safe, I'd put it like this:
    sub merge { my %hash; @hash{ @_ } = @_; @hash{ sort keys %hash }; }

    Update: last line was originally map $hash{ $_ }, sort keys %hash;

      Sorry for the reply to an old-node, but I was wondering what you meant by "reference-safe", and thought you might mean something like the following (which I thought might emit a "Modification of a read-only value" error if the $_ in the for loop were still referring to the keys of the hash), but it seems to work just fine without error (tested on 5.6 and 5.8):
      #!/usr/bin/perl use strict; use warnings; sub merge { my %hash; @hash{@_} = (); sort keys %hash; } my @array1 = qw(a b c d e); my @array2 = qw(c d e f g); for (merge(@array1, @array2)) { $_++; print "$_\n"; }

        Your code will return stringified references if any were part of the list it was passed. The code I wrote preserves references as references. It’s not a huge deal – after all, while you may sometimes want a list of unique references, it’s unlikely that you’ll want them sorted on the stringified value of the reference. But it might still save you from getting bitten somewhere else, depending on how locally the function is used.

        Makeshifts last the longest.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://114929]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-20 01:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found