How does a perfect hash function work?
How does a perfect hash function have collision-resistant in this case?


Well, when we select a perfect hash function, we take as inputs a set of messages $M_1, M_2, M_3, ..., M_n$, and use them to select a hash function for which $H(M_i) \ne H(M_j)$ (if $i \ne j$)

Now, according to the pigeon hole principle, the output of $H$ must be at least $\log_2 n$ bits long; as $n$ is typically not that huge, that is not a practical problem.

Now, there may be messages $M$ not in the original set for which $H(M) = H(M_i)$ for some $i$; that's ok, as the collision freeness of the perfect hashing function is defined only for the original set of messages, not any additional messages.

And, as cryptostatis has mentioned, we don't have much use for perfect hashing functions in cryptography.  We do use collision resistant hash functions; however by that, we mean that while collisions $H(M) = H(M')$ do exist, it is difficult to find them.