in reply to How to assign a hash from an array?

Ok, let's say that @calarray (not a good name by the way, very easy to type it wrong) has alreay been populated, and populated with tainted user input to make things icky:
my @line = qw(foo;bar baz;qux user;errors;suck trust; ;no-one ;);
You can use this snippet to only get those items that have one token before the first semi-colon, and also one token after that semi-colon:
my %hash = grep !/^$/, map { ($a,$b) = $_ =~ /^([^;]+);([^;]+)/; ($a,$b); } @line;
I chose not to worry about possible whitespace, it is ugly enough as it is. The idea is to do as guha rightfully said, use a regex. The map filters out the key and value pairs, but because of tainted user input, we still get an undefined key (actually, three candidates that overwrite each other). The grep takes care of those.

Warning: I use $a and $b in this example. These variables are meant to be used with sort, but i see no problem in using them here - you don't even have to declare them. Just don't be tempted to use them for any task more than temporary. In fact, you should probably just stick to only using them for sort. ;)

Also, a time saving tip: If you want to quickly see if the hash (or array or any other data strucure) contains what you think it should, use Data::Dumper (thanks to guha for clearing up my blunder - see below ;))

use Data::Dumper; print Dumper \@array; print Dumper \%hash; print Dumper $reference;
From the first two code snippets, the variable %hash should look like:
$VAR1 = {
          'foo' => 'bar',
          'baz' => 'qux',
          'user' => 'errors'
        };

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: (jeffa) Re: How to assign a hash from an array?
by guha (Priest) on Mar 11, 2002 at 08:53 UTC
    use Data::Dumper;

    print \@array;
    print \%hash;
    print $reference;

    Won't work.

    You'll need to type
    use Data::Dumper; print Dumper(\%hash);

    Furthermore recent postings have indicated that use of the special variables for sort, $a and $b, gets in the way of DWIM and should best be avoided for general use.

    ---
    I would like to change the world but God won't let me have the source code.
      Thanks for bringing the Dumper error to my attention.

      Now, as for $a and $b - i did already give a warning about them. However, i feel that in this case - it's ok to use them. I never declared them, see the difference? Those recent postings you refer to declare $a and $b as lexical variables.

      If you disagree, then please show me how my example would 'get in the way of DWIM'.

      Thanks again. :)

      jeffa

      L-LL-L--L-LL-L--L-LL-L--
      -R--R-RR-R--R-RR-R--R-RR
      B--B--B--B--B--B--B--B--
      H---H---H---H---H---H---
      (the triplet paradiddle with high-hat)