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

Dear Monks,

For a large calculation, I need to have some adjustement according to the memory available. How I can catch the out of memory errors at run time ?.

Thanks,
artist.

Replies are listed 'Best First'.
Re: Catching "out of memory " error
by perrin (Chancellor) on Mar 25, 2003 at 21:11 UTC
    You can't catch an "out of memory" error. It means what it says: there's no more memory to use! One thing you could try is measuring the amount of memory your process uses as you go and aborting before you run out of memory.
Re: Catching "out of memory " error
by OM_Zen (Scribe) on Mar 25, 2003 at 21:53 UTC
    Hi,

    This might be a lateral idea or something and not a solution to the requirement .

    The setting of the  $^M pre-defined variable which can be a setting for an emergency memory pooling of which more details are in

    perldoc perlvar for details on this variable

Re: Catching "out of memory " error
by bluto (Curate) on Mar 25, 2003 at 21:54 UTC
    As stated by others, you can't do this with any consitency. You may however be able to estimate how much memory a given calculation will use by running smaller calculations and watching the memory usage (e.g. with 'ps'). You'll probably want to limit your memory usage to some percentage of total real memory (rather than virtual memory) for best performance, but YMMV.

    bluto

Re: Catching "out of memory " error
by Zaxo (Archbishop) on Mar 25, 2003 at 20:58 UTC

    The usual method for throw and catch of exceptions is to eval, then test $@.

    use Errno; eval { # ... }; if ($@ == ENOMEM) { # ... }

    Update: Oops. It's not really the little things that bite the worst ;-)

    After Compline,
    Zaxo

Re: Catching "out of memory " error
by Aristotle (Chancellor) on Mar 30, 2003 at 19:35 UTC
    Try not to run out of memory in the first place. Devel::Size will help you estimate.

    Makeshifts last the longest.

Re: Catching "out of memory " error
by dragonchild (Archbishop) on Mar 25, 2003 at 20:53 UTC
    Learn about eval. It is the (current) way to trap all run-time errors.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      Well... no. eval won't catch out of memory errors, as they're generally very fatal. It may, occasionally, work, but I wouldn't count on it at all.