sub imgtype { my $file = shift; my %types = ( 'BMP' => qr/^BM/, 'GIF' => qr/^GIF8[79]a/, 'JPEG' => qr/^\xFF\xD8/, 'PNG' => qr/^\x89PNG\x0d\x0a\x1a\x0a/, 'PPM' => qr/^P[1-6]/, 'SVG' => qr/^<\?xml/, 'TIFF' => qr/^MM\x00\x2a|^II\x2a\x00/, 'XBM' => qr/^#define\s+/, 'XPM' => qr/(^\/\* XPM \*\/)|(static\s+char\s+\*\w+\[\]\s*=\s*{\s*"\d+)/, ); if (-e $file ) { open(my $fh, '<', $file) or die $!; read($fh,my $head,11); close($fh); while ( my ($type,$match) = each %types ) { if ( $head=~m/$match/ ) { return $type; } } return undef; }else{ return undef; } } #### my %ALLOWED = ('GIF' => 1 ,'JPEG' => 1 ); # can be called like this my $Type = imgtype('some/location/image'); if ( defined $Type && $ALLOWED{$Type} ) { # process image }else{ # delete it or do whatever you want with it }