I think what you are looking for is:
if( $test =~ /^\d{4}$/ ) {
...
}
This will match:
'^': anchor start of string
\d{4}: exactly 4 digits
$: anchor end of string
if you know it is always going to be digits, then
length would probably be eaiser:
if( length($test) == 4 ) {
...
}