Perl shareable memory is very easy to use, see Perl Shareable Memory Examples, however, in regular use case, it only can be directly used for simple variables, such as scalar, hash, 1 D array etc.. For complex data structure, like variable harsh in an array, $c[$i]{$key}, or array in a hash, perl shareable memory doesn't directly offer the solution. 

However, it can be done indirectly, here is it.

Tie a variable to a shareable segment.

my $student_handle= tie our %s_student, 'IPC::Shareable', 'stud', \%option ;

Define a student card

our %stud_stru= (
  '0' => 'name',
  '1' => 'studentid',
  '2' => 'class',
  '3' => 'gender',
  '4' => 'age',
);

Suppose you've put whole class students info into a array called @student, and it's a combined hash array:

$student[0]{'name'}="James";
$student[0]{'studentid'}=98001;
...

Here is the function to write the array @student to shareable memory.

sub write_share_hash
{
  my @array= @{$_[0]};
  my %stru= %{$_[1]};
  my ($str,$key,$name);
  $student_handle->shlock();
  for (my $i=0;$i<=$#array;$i++) { # Conver the hash into a string
    $str="";
    foreach $key (sort keys %stru) {
      $str.= $array[$i]{$stru{$key}}.",";
    }
    $str =~ s/,$//g ;
$name=$array[$i]{'name'};
    $s_student{$name}=$str;
  }
  $student_handle->shunlock();
}

The main idea is to convert the hash in the array into a string, make the student card into a regular array or hash variable, then save it to shareable memory. Isn't it easy?

Similarily, when read from the shareable memory, use the function below:

sub read_share_hash
{
  my %hash   = %{$_[0]};
  my $handle_tmp = $_[1];
  my %stru   = %{$_[2]};
  my @array=();
  my ($key,@str_array,$subkey);
  $handle_tmp->shlock();
  foreach $key (keys %hash) {
    @str_array=split(/,/,$hash{$key}) ;
    foreach $subkey (sort keys %stru) {
      $array[$key]{$stru{$subkey}}=$str_array[$subkey];
    }
  }
  $handle_tmp->shunlock();
  return(@array);
}

 

 

 

 

 

Comments powered by CComment