Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

drhyde (1683)

  (email not shown publicly)

Journal of drhyde (1683)

Saturday April 26, 2003
03:08 PM


[ #11860 ]

sub zipn {
    local $[ = 0;
        map {
            my $index = $_;
            map {
                defined($_[$_][$index]) ?
                    $_[$_][$index] :
            } 0..$#_
        } 0 .. maximum(map { $#{$_[$_]} } 0..$#_)

sub maximum {
    local $[ = 0;
    ($#_ == 1) ?
            ($_[0] >= $_[1]) ?
                $_[0] :
        ) :
        maximum(maximum($_[0], $_[1]), @_[2..$#_]);

Call it like so:

zipn([1,2,3], [4,5,6], [7,8,9,10])

and it'll return this:


What fun! Note that if any of the arrays are too short, it fills in the blanks with the empty string, cos that's what I needed at the time. Changing it to emit undefs would be trivial. And yes, the maximum function is hideously inefficient, but I enjoy recursion.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • This is unnecessary, and in fact, I'm surprised it's not a runtime error. $[ is lexical. Quoting perlvar :
    As of release 5 of Perl, assignment to $[ is treated as a compiler directive, and cannot influence the behavior of any other file.
    • If I had packaged that up in a neat little module on its own then yes, I wouldn't have bothered, but I didn't, and if someone had cut n' pasted it into some of their code where they'd been messing with $[, then I need to set it myself.

      I fail to see anything in that snippet from the man page which suggests that it is either unnecessary or an error.
      • You don't understand me : $[ acts as a pragma. It's not file-scoped, it's lexical. Using local() on it is a null operation. The perlvar phrasing is misleading, I'll see how to change it (except the part where it is said that its use is highly discouraged).
        • OK, I was wrong, it appears that $[ leaks out of some scopes at compile time, so it's not strictly equivalent to a pragma. So the following prints, undocumentedly, '001' :

          print $[;
          if (0) { local $[ = 1; }
          print $[;
          if (0) { $[ = 1; }
          print $[;
  • max() is in the module List::Util []. Depending on the platform, it may be in XS, or in plain perl (the fallback). Anyway, it's not necessary to reinvent that wheel.
    • If I'd wanted to do things the "right" way, I wouldn't have written "And yes, the maximum function is hideously inefficient, but I enjoy recursion.". Obviously.