Steve_BZ has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

Hi have an array of items returned from a dialog box. For most items, I just get a scalar corresponding to the value of the GUI control, but for controls which return multiple values (eg a multi-value list-control or multi-value combo-box) I have an array. How can I tell which is which?

Eg I might get the variables returned with the follwoing values:

{attributes}{control1} = "abc" {attributes}{control2}[0] = "cde" {attributes}{control2}[1] = "fgh"
I tried using exist as follows:
if (exists $dialog->{attributes}[0]){ ... do something.... }

But this just gives a error.

I'm sure the answer is obvious, but at the moment it's not hitting me.

Regards

Steve

Replies are listed 'Best First'.
Re: How to distinguish an array data type from a scalar data type in a complex hash.
by almut (Canon) on Mar 13, 2010 at 11:13 UTC
    #!/usr/bin/perl -l $dialog->{attributes}{control1} = "abc"; $dialog->{attributes}{control2}[0] = "cde"; $dialog->{attributes}{control2}[1] = "fgh"; for my $control (keys %{ $dialog->{attributes} }) { if (ref $dialog->{attributes}{$control} eq 'ARRAY') { print "@{ $dialog->{attributes}{$control} }"; } else { print $dialog->{attributes}{$control}; } } __END__ abc cde fgh

    Or, with an intermediate variable (better readable IMHO):

    for my $control (keys %{ $dialog->{attributes} }) { my $val = $dialog->{attributes}{$control}; if (ref $val eq 'ARRAY') { print "@$val"; } else { print $val; } }

    And in case there could also be other types (such as hashrefs), you should either test for them, too, or at least write

    ... } elsif (!ref $val) { print $val; }

    for the simple scalar values.

      Thank you Almut, just what I needed.

      Regards

      Steve

Re: How to distinguish an array data type from a scalar data type in a complex hash.
by Anonymous Monk on Mar 13, 2010 at 10:41 UTC