Verilog: use calculated variable as length or index of another variable
For truncation, you can do a shift and mask operation. 

somefunction = Z &amp; ((2&lt;&lt;x)-1);


In your second example, replicating 1'b0 is unnecessary and doesn't accomplish anything. I find that the case is many other examples. You can always revert to a for loop if necessary.