#!/usr/bin/perl use strict; my $encoding = 'UTF-16'; my $Usage = "Usage: $0 [-BE|-LE] file.u16\n"; if ( @ARGV and $ARGV[0] =~ /^-([BL]E)$/ ) { $encoding .= $1; shift; } die $Usage unless ( @ARGV == 1 and -f $ARGV[0] ); my $filename = pop @ARGV; # if user didn't specify byte order, let's check the input file if ( $encoding eq 'UTF-16' ) { my $first_short; open( F, "<", $filename ) or die "$filename: $!"; my $n = sysread( F, $first_short, 2 ); die "sysread failed on $filename" unless ( $n == 2 ); if ( $first_short == pack( 'S', 0xfeff ) or $first_short == pack( 'S', 0xfffe ) { # it's a BOM, and using ":encoding(UTF-16)" is fine } else { die "$filename has no BOM; please specify byte order\n$Usage"; } } close F; open( F, "<:$encoding", $filename ); # ... and go to work...