Search code examples
verilogsystem-verilog

How to separate by special keyword in merged associative array without other library?


I'm trying to find the array which has the specific keywords in merged associative array in SystemVerilog.

For example, I have the 4 arrays:

bit [31:0] arrayA[string];
bit [31:0] arrayB[string];
bit [31:0] arrayC[string];
bit [31:0] arrayD[string];

// Initialize the arrays
arrayA["key1"] = 100;
arrayA["key2"] = 200;
arrayB["door2"] = 300;
arrayB["door3"] = 400;

// Merge the arrays into arrayC
foreach (arrayA[key]) begin
  arrayC[key] = arrayA[key];
end

foreach (arrayB[key]) begin
  arrayC[key] = arrayB[key];
end

I have merged all into arrayC[], and I want to find the array elements which have only the "door" string in the array keys.

But, SystemVerilog there is no strtok() method.

// Separate the merged array by keyword
foreach (arrayC[key]) begin
  string keyword;
  keyword = strtok(key, "door");  // strtok does not work.

  foreach (arrayC(key)) begin
     if (arrayC.exists(keyword)) 
        arrayD[key] = arrayC[key];
  end

end

I want to create a new arrayD[] from a merged arrayC[] with similar string keys that contain only the string I want, such as "door".

I want arrayD to have only these elements:

  arrayB["door2"] = 300;
  arrayB["door3"] = 400;

because arrayD was filtered to only have an array with the string "door".

How to find a special keyword in a merged associative array in SystemVerilog without a 3rd party library?


Solution

  • Use substr to filter the keys for the ones which begin with the string "door". Refer to IEEE Std 1800-2017, section 6.16.8 Substr().

    module tb;
    
    bit [31:0] arrayA[string];
    bit [31:0] arrayB[string];
    bit [31:0] arrayC[string];
    bit [31:0] arrayD[string];
    
    initial begin
    
    // Initialize the arrays
    arrayA["key1"]  = 100;
    arrayA["key2"]  = 200;
    arrayB["door2"] = 300;
    arrayB["door3"] = 400;
    
    // Merge the arrays into arrayC
    foreach (arrayA[key]) begin
        arrayC[key] = arrayA[key];
    end
    
    foreach (arrayB[key]) begin
        arrayC[key] = arrayB[key];
    end
    
    // Separate the merged array by keyword
    foreach (arrayC[key]) begin
        if (key.substr(0, 3) == "door") begin
            arrayD[key] = arrayC[key];
        end
    end
    
    $display("arrayD %p", arrayD);
    
    end
    
    endmodule
    

    Prints:

    arrayD '{"door2":300, "door3":400 }