in reply to Re: Add new data to array
in thread Add new data to array

Why this,

my $add_in = $add_ins[0];

couldn't be like this?
my $add_in = (); my @$add_in = $add_ins[0];

Thanks!

Replies are listed 'Best First'.
Re^3: Add new data to array (updated)
by AnomalousMonk (Archbishop) on Mar 17, 2020 at 20:40 UTC

    WRT this code, because  $add_ins[0] is a hash reference (@add_ins is an array of hash references) and so  $add_in would become (by autovivification) a reference to an array holding a single element: a hash reference. The expression  $add_in->{name} would then have to become  $add_in->[0]{name} which would be possible, but a useless complication.

    Update 1: Normally, a statement like
        my @$add_in = $add_ins[0];
    would be written
        my @$add_in = ($add_ins[0]);
    using parentheses to make the RHS a proper list, but in the special case of single-element array assignment, Perl allows the parentheses to be dispensed with. In
        my $add_in = ();
    the parentheses have no effect; the statement is equivalent to
        my $add_in;

    Update 2: BillKSmith covers a point which I neglected to mention: the statements
        my $add_in = ();
        my @$add_in = $add_ins[0];
    are syntactically incorrect due to the use of the my declarator in the second statement. However, if this operator is removed, what's left is code that can be made to compile and to run without warnings and to work, albeit IMHO in an ugly, confusing and inefficient manner as discussed above.

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @add_ins = ({ qw(foo bar) }, { qw(biz boz) }); ;; my $add_in = (); @$add_in = $add_ins[0]; dd $add_in; print $add_in->[0]{'foo'} " [{ foo => "bar" }] bar


    Give a man a fish:  <%-{-{-{-<

Re^3: Add new data to array
by BillKSmith (Monsignor) on Mar 17, 2020 at 21:09 UTC
    I do not understand what you mean. Your code is not valid Perl.
    >type tryit.pl use strict; use warnings; my $add_in = (); my @$add_in = $add_ins[0]; >perl tryit.pl "my" variable $add_in masks earlier declaration in same scope at tryit +.pl line 4 . Can't declare array dereference in "my" at tryit.pl line 4, near "$add +_in =" Global symbol "@add_ins" requires explicit package name (did you forge +t to decla re "my @add_ins"?) at tryit.pl line 4. Execution of tryit.pl aborted due to compilation errors.

    I defined the array @add_ins to force grep to run in list context. Execution of grep returnes a list (which contained only one element) and assigned it to @add_ins. The statement my $add_in = $add_ins[0]; assigns the value of that element to the scalar $add_in. Note that the value is a reference to the hash which contains the data which is to be added to every hash. AnomolousMonk accomplished the same thing by using the extra parenthesis to force list context and used list assignment to extract the single reference.

    Bill