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

Is there an easy way to tell the size of a scalar (preferably in bytes)?

And while I'm thinking of it, if I go grab a file over HTTP using LWP::UserAgent, is there an easy way to tell the size of what I downloaded?

Replies are listed 'Best First'.
Re: Size of scalar in bytes
by hardburn (Abbot) on Nov 17, 2003 at 17:41 UTC

    Is there an easy way to tell the size of a scalar (preferably in bytes)?

    use bytes; my $len = length $var;

    And while I'm thinking of it, if I go grab a file over HTTP using LWP::UserAgent, is there an easy way to tell the size of what I downloaded?

    Servers should (but aren't required) to send a Content-Length header. If the server didn't send it, then there isn't a way you can tell the size until you've already downloaded it. Most servers will send that header, but you should code in such a way that it gracefully handles the lack of Content-Length.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    : () { :|:& };:

    Note: All code is untested, unless otherwise stated

Re: Size of scalar in bytes
by ysth (Canon) on Nov 17, 2003 at 17:55 UTC
    $chars = length($scalar); # length in characters # what you probably were looking for
    $bytes = do {use bytes; length($scalar)} # length in bytes # bytes may be != chars for unicode strings
    $approx_memory_used =Devel::Size::size($scalar) # including perl's overhead
A reply falls below the community's threshold of quality. You may see it by logging in.