Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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

by Aristotle (Chancellor)
on Sep 27, 2001 at 13:30 UTC ( [id://115039]=note: print w/replies, xml ) Need Help??


in reply to Re: A C-like brain in a Perl-like world
in thread A C-like brain in a Perl-like world

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;

Replies are listed 'Best First'.
Re^3: A C-like brain in a Perl-like world
by runrig (Abbot) on Jun 06, 2005 at 23:57 UTC
    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://115039]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-04-19 22:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found