SHA256 prepares the input data by appending padding and a length field to the end of it, so the total input ends up being a multiple of 64 bytes.

The "data" string you're given has this preparation step done already, which means you can't just feed it into a normal hashing function like sha256_hex and expect the right result (because sha256_hex will do this preparation step again).

Read about how SHA256 works. The midstate is the internal state after processing the first 64-byte block.

(Also, in the line of your code that swaps the data, you meant to use $data_raw rather than $data, right?)

I was doing this because there are no perl module allow me to access the sha256 internals (at least not without saving the state to disk).

Does it means there are no way using the OS-provided crypto function that do complete sha256 hash work?I think the "via" code do the extra padding as well, or does it?

ignore the midstate and only use the first 80 bytes of the data if you are using a standard sha256 library. I have used the libgcrypt this way also (it is slow tho). You can also ignore the hash/hash1 fields passed, just use your own. Then return the data with your nonce inserted if you find a candidate hash.

Using standard sha256 libraries you will probably also need to undo the byte swaps on the data field. And reswap the data to return it.