in reply to variable list assignment

If you really don't like the temporary array - doesn't seem so bad to me - you could use something like:

my $i = 0; # or whatever $record[$i++]->{bytes} = $_ for get_bytes($num);

or perhaps, if you're just building the list:

push @record, map { {bytes => $_} } get_bytes($num);

but that won't be much good if you're working with an existing data structure. In that case i don't see a way of shrinking it to one line - and suspect that even if you find one, you'd regret the obfuscation later.

update just tried mr robot's solution and found, to my surprise, that the double curlies aren't required. I would have expected

@a = map { k => $_ } (1..3);

to give you (k,1,k,2,k,3), but no: it creates an array of hashrefs. so either that isn't a block at all - but where's the comma? - or there is such a thing as hash context after all. nice bit of dwimming. still borks any other key that previously existed in the hash, though.

update^2 don't know what i was thinking there. sauoq is quite right. odd that i remember it working, but clearly it doesn't :(

Replies are listed 'Best First'.
Re: Re: variable list assignment
by tantarbobus (Hermit) on Aug 03, 2002 at 19:52 UTC
    Here it is in one line, but this has the (unfortunate side effect/added feature) of choping @array to $n entries.
    use Data::Dumper; my @array; my $n = 10; sub get_bytes { map {rand($_)} 1..$_[0] } $array[$_]->{bytes} = 'fake' for (1..$n); @array = map {$array[0]->{bytes}=$_;shift @array} get_bytes($n); print Data::Dumper::Dumper(\@array);
Re: Re: variable list assignment
by sauoq (Abbot) on Aug 05, 2002 at 04:01 UTC
    update just tried mr robot's solution and found, to my surprise, that the double curlies aren't required. I would have expected

    Actually, you missed a comma that impossiblerobot's code contained. His code was:

    my @record = map { bytes => $_ }, get_bytes($num);
    and that comma between the arguments to map makes map interpret the first argument as an EXPR not a BLOCK.

    BTW, my perl (5.6.1) chokes on the code in your update:

    perl -e '@a = map {k => $_} (1..3)' syntax error at -e line 1, near "}("
    -sauoq
    "My two cents aren't worth a dime.";