Creating arrays dynamically in Perl

后端 未结 4 1731
旧巷少年郎
旧巷少年郎 2020-12-07 02:04

I want to create arrays dynamically based on the user input. For example, if the user gives input as 3 then three arrays should be created with the name @message1

4条回答
  •  长情又很酷
    2020-12-07 02:16

    Creating new named arrays dynamically is almost never a good idea. Mark Dominus, author of the enlightening book Higher-Order Perl, has written a three-part series detailing the pitfalls.

    You have names in mind for these arrays, so put them in a hash:

    sub create_arrays {
      my($where,$n) = @_;
    
      for (1 .. $n) {
        $where->{"message$_"} = [];
      }
    }
    

    For a quick example that shows the structure, the code below

    my $n = @ARGV ? shift : 3;
    
    my %hash;
    create_arrays \%hash, $n;
    
    use Data::Dumper;
    $Data::Dumper::Indent = $Data::Dumper::Terse = 1;
    print Dumper \%hash;
    

    outputs

    $ ./prog.pl
    {
      'message2' => [],
      'message3' => [],
      'message1' => []
    }

    Specifying a different number of arrays, we get

    $ ./prog.pl 7
    {
      'message2' => [],
      'message6' => [],
      'message5' => [],
      'message4' => [],
      'message3' => [],
      'message1' => [],
      'message7' => []
    }

    The order of the keys looks funny because they're inside a hash, an unordered data structure.

    Recall that [] creates a reference to a new anonymous array, so, for example, to add values to message2, you'd write

    push @{ $hash{"message2"} }, "Hello!";
    

    To print it, you'd write

    print $hash{"message2"}[0], "\n";
    

    Maybe instead you want to know how long all the arrays are:

    foreach my $i (1 .. $n) {
      print "message$i: ", scalar @{ $hash{"message$i"} }, "\n";
    }
    

    For more details on how to use references in Perl, see the following documentation:

    • Mark's very short tutorial about references, or perldoc perlreftut
    • Perl references and nested data structures, or perldoc perlref
    • Perl Data Structures Cookbook, or perldoc perldsc

提交回复
热议问题