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

I am trying to call a function only if a label doesn't exist as below but running into syntax error,Can some pls advise?

call_view () unless not exists "Label__$options{r}_$date"; exists argument is not a HASH or ARRAY element at c:\perl.pl line 136

Replies are listed 'Best First'.
Re: calling a function based on a condition
by GrandFather (Saint) on Mar 14, 2011 at 00:09 UTC

    A label where? exists tests to see if specific elements of a hash or an array exist or not. Your code makes no mention of an array or hash - exactly as the error you have shown says.

    You may like to show us a little more code so we may be able to see what is causing you grief. A small self contained example script would be most appropriate. See I know what I mean. Why don't you? for hints.

    True laziness is hard work
Re: calling a function based on a condition
by cdarke (Prior) on Mar 14, 2011 at 09:25 UTC
     "Label__$options{r}_$date" is a string, exists tests for the presence of a hash key. You could do an exists on $options{r}, but not a string.

    Your use of the term 'label' is confusing. In Perl, a label is a loop identifier, see perlsyn and, unless you are playing with eval magic, is hardcoded. Maybe you expect us to remember some previous post you did? Problems with that is that you are signed-on as Anonymous Monk, so we can't look back at your previous posts to see what you are doing.
Re: calling a function based on a condition
by Khen1950fx (Canon) on Mar 14, 2011 at 01:40 UTC
    unless is a statement modifier that executes the statement if that statement is false. You are essentially going into reverse; however, unless not reverses the reverse, basically saying that it's true. That's not what you want. The correct expression to use would be unless exists. For example:
    #!/usr/bin/perl use strict; use warnings; my %options; call_view() unless exists $options{'r'}; sub call_view { print "doesn't exist.\n"; }
    call_view() is called because $options{'r'} doesn't exist.
      reverses the reverse
      reminds me of a UK West Country phrase
      theze bin an gotten whur thee casn't back'n assn't
      You would think that it wouldn't be possible but every driver knows that it is.

      I have the same trouble with unless. It is very simple but I too often get it wrong. I tend to stick with

      ... if not exists $options{'r'};
      Not as elegant but it tends to increase my chances :-)