class Register ;
string name;
rand bit [3:0] rank;
rand bit [3:0] pages;
function new(string name);
this.name = name;
endfunction
function void print();
$display("name=%s rank=%0d pages=%0d",name, rank, pages);
endfunction
endclass
module tb;
Register rt[4];
string name_arr[4]={"alexa","siri","google home","cortana"};
initial begin
$display(
"---------initial value-----------"
);
foreach (rt[i]) begin
rt[i]=new(name_arr[i]);
rt[i].randomize();
rt[i].print;
end
$display(
"---------sort by name------------"
);
rt.sort (x) with (x.name);
foreach (rt[i]) rt[i].print;
$display(
"---------sort by rank,pages---------"
);
rt.sort (x) with ({x.rank,x.pages});
foreach (rt[i]) rt[i].print;
$display(
"---------sort by pages------------"
);
rt.sort (x) with (x.pages);
foreach(rt[i]) rt[i].print;
end
endmodule
编译结果
# Loading sv_std.std
# Loading work.testbench_sv_unit(fast)
# Loading work.tb(fast)
#
# vsim -voptargs=+acc=npr
# run -all
# ---------initial value-----------
# name=alexa rank=13 pages=11
# name=siri rank=11 pages=15
# name=google home rank=12 pages=10
# name=cortana rank=8 pages=3
# ---------sort by name------------
# name=alexa rank=13 pages=11
# name=cortana rank=8 pages=3
# name=google home rank=12 pages=10
# name=siri rank=11 pages=15
# ---------sort by rank,pages---------
# name=cortana rank=8 pages=3
# name=siri rank=11 pages=15
# name=google home rank=12 pages=10
# name=alexa rank=13 pages=11
# ---------sort by pages------------
# name=cortana rank=8 pages=3
# name=google home rank=12 pages=10
# name=alexa rank=13 pages=11
# name=siri rank=11 pages=15
# exit
# End time: 07:55:56 on Mar 31,2022, Elapsed time: 0:00:01
# Errors: 0, Warnings: 1