开发者

Perl threading with hash of arrays

I am trying to share a hash of arrays with threads::shared module as below.

use warnings;
use strict;
use threads;
use threads::shared;

my @allThreads;
share (my %array);

foreach ('alpha', 'beta', 'gamma')
{
    $name = $_;
    push @allThreads, threads->new(\&doWork, $name);
}

foreach my $thread (@allThreads){ $thread->join; } # Wait for all threads to join.

sub doWork
{
    $tempName = shift;
    my @results = `/bin/ls /home/*`;
    doMoreWork($tempName, @results);
}

sub doMoreWork
{
    my $myName = shift;
    my @tempResults = @_;
    foreach (0 .. $#tempResults)
    {
        if($tempResults[$_] =~ /(\w+)/)
      开发者_运维技巧  {
            my $x = $1;
            $array{$x} = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
        }
    }
}

foreach (keys %array)
{
    print "$array{$_}->[3]\n";
}

I get the following error:

Can't use string ("11") as an ARRAY ref while "strict refs" in use at myCode.pl.

I need to sort this shared hash of arrays by an array element.

Any help would be appreciated.


Your doWork function is evaluating @temp in scalar context. So it is effectively doing $array{$tempName} = 11.

Also you can omit the temp variable, since [ ... ] already creates an array reference.

sub doWork
{
    $tempName = shift;
    $array{$tempName} = [1 .. 11];
}

[edit]

This version of doMoreWork runs at least:

sub doMoreWork
{
    my $myName = shift;
    my @tempResults = @_;
    if(/(\w+)/)
    {
        my $x = $1;
        share (my @temp);
        @temp = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
        $array{$x} = \@temp;
    }
}

...but does not do anything useful because /(\w+)/ is not matching anything meaningful. I cannot tell what you trying to do here...


You can always try using my simplifying project found here https://github.com/PabloK/ThreadedArray It aims to simplify work over a set of elements in an array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜