in reply to Joining an array

So, "why?" /me said to myself, "Why can't Perl chew on this?"

my $i = 0; my $str = "$arr[$i]=$arr[++$i]" x($#arr/2);

or this?

my $i = 0; my $str = "$arr[$i]=$arr[++$i]" x($#arr/2) . "&";

Now, of course the first snippet left the question of inserting the ampersands un-resolved, but that's OK, because Perl wants an int after the x operator and 5/2 isn't likely to ever be an int. Then, the second suffers the same defect ... and inserts the ampersand only AFTER printing the second name=John; a 'gotcha' for this nutty idea that I don't see a way around (in this approach).

But, the idea perked on, leading to this, just because TIMTOWTDI:

#!/usr/bin/perl use strict; use warnings; use 5.014; # desired: name=John&number=7&status=unknown my @arr = qw(name John number 7 status unknown); my $i = 0; my $str = "$arr[$i]=$arr[++$i]"; $str .= "&$arr[++$i]=$arr[++$i]"; $str .= "&" . "$arr[++$i]=$arr[++$i]"; say $str;

Output? As specified.

Replies are listed 'Best First'.
Re^2: Joining an array
by tangent (Parson) on Feb 11, 2012 at 02:06 UTC
    Thanks ww. I should have mentioned though that there are a variable number of elements in the array.
      Variable number of elements is not a problem; it's just a circumstance that demands a little more code....

      So, let's see... . o O

      We know how to count the elements, $#arr... so that means we'll need to repeat the next-to-last line $#arr/2 times.

      Oops. Not an integer. Well, we knew that already too, but after we've printed the first pair, we should need to repeat either of the next two lines ( ($#arr/2) -1 ) times. Or we could start with ( ($#arr +1)/2 ). Either way, Shazam! The problem of an unknown number of pairs in the array is (almost) solved, except for the trivial act of actually writing the code.

      Do you smell a loop coming? I do.

      Again, this is a case of TIMTOWTDI that's NOT worth pursuing, except for the mental exercise (or maybe, an obfuscation contest). The solutions with a module that's designed to do just what you want are clearly the way to go in the real world.

      It does, however, have a smidgen of value for readers here in the Monastery: it emphasizes the need for precision and completeness in problem statements.

        Point taken about problem statements ww. Whatever anyone else gets out of it I for one have learnt a geansaí load from this one thread. I would never have thought of using sprintf, and as for tieing a scalar... and I can already see other places where these can be used.

        -- geansaí is the Irish word for jumper, as in "I got a geansaí load of apples from that orchard" - as many apples as you can carry tucked into your jumper. Funnily enough, the Jamaican word "gansy" has exactly the same meaning.