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

Anyway to put a counter on my warning messages?
open ( F, $variable ) || warn "Can not open $variable: $!\n";
Like this??
open ( F, $variable ) || warn "Can not open $variable: $!\n, $counter +++";

Replies are listed 'Best First'.
Re: Warning counter
by sauoq (Abbot) on Jul 01, 2003 at 16:55 UTC

    You almost had it... You just can't increment inside quotes like that. But, warn takes a list just like print does.

    open ( F, $filename ) or warn "Cannot open $filename (", $counter++, " +): $!\n";

    If you want, you can use a do block to do more complex things if the open fails.

    open ( F, $filename ) or do { $counter++; warn "Cannot open $filename ($counter): $!\n"; # And whatever else you want... };
    -sauoq
    "My two cents aren't worth a dime.";
    
      Warn takes a list! Heck, die takes a list, too! Has this always been so? All this time I've been using . to concat.

      Where did I get the idea that it had to be one string?

      Not that it matters a whole lot, but it's just slightly nicer to use commas.

        Has this always been so?
        Indeed it has. If you look at the top of the warn and die docs you'll see the prototype func LIST meaning it takes a list. Although this isn't terrifically relevant to the output as the list is concatenated into a single string and the same behaviour goes for the arguments to the __WARN__ and __DIE__ signal handlers. So it's really just for your convenience, such is perl's way :)
        HTH

        _________
        broquaint

      thank you to both of you.
Re: Warning counter
by dws (Chancellor) on Jul 01, 2003 at 16:51 UTC
    Would
    open(F, $variable) or warn "$variable: $! (" . $counter++ . ")\n";
    do what you want? I left off the "Can not open" part because the error message in $! is almost always sufficient without adding extra verbiage.

    Note that you're setting yourself up for another problem. Unless you're using $counter to decide whether F is really open, you'll get an error downstream when you try to read or write using F.