Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I need to know the number of bytes a file would be if I printed a string to a file, before I create the file.

How would one go about doing this?

Replies are listed 'Best First'.
Re: Bytes in a String
by Errto (Vicar) on Jul 03, 2005 at 04:20 UTC
    It depends on the output encoding you intend to use for that file. If the encoding is utf-8, then the anonymous post above is correct, because length will return the number of bytes in UTF-8 when use bytes is in effect. But if your encoding is something else, the result may be different:
    use strict; use warnings; my $x = "abcdefg"; print length $x, "\n"; { use bytes; print length $x, "\n"; } open my $fh, ">:encoding(ucs-2)", "out.txt" or die $!; print $fh $x; close $fh; print +(stat "out.txt")[7], "\n"; #print size of file in bytes __END__ 7 7 14
    A more generic technique for determining the length of a string in a given output encoding:
    use Encode qw/encode/; my $x = "abcdefg"; print length(encode("ucs-2", $x)), "\n";
      CRLF translation may also need to be accounted for.
Re: Bytes in a String
by Anonymous Monk on Jul 03, 2005 at 02:34 UTC
    #!/usr/bin/perl -l $a = chr(1222) . "abc" . chr(2201); print length($a); { use bytes; print length($a); } print length($a); __END__ 5 8 5