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

This is such a stupid question but I am having problems with it.

All I am trying to do is determine the length of a string, and then, if it is less than 6 chars, run a subroutine. I keep getting an error. I'm not sure why. Here's the code.

$errmsg = "Too Few Characters in Company Login Name";
&err if (length($compname) < 6);

Replies are listed 'Best First'.
Re: Simple length question
by mrbbking (Hermit) on Jan 28, 2002 at 21:53 UTC
    What error do you get? The code works for me, after filling in the blanks.
    #!/usr/bin/perl -w use strict; my $errmsg = "Too Few Characters in Company Login Name"; sub err{ print $errmsg; } my $compname = "Sears"; &err if (length($compname) < 6); # prints $errmsg $compname = "Sears Roebuck"; &err if (length($compname) < 6); # doesn't.
Um . . .
by Fletch (Bishop) on Jan 28, 2002 at 21:48 UTC

    Perhaps

    • you could give the text of the error message . . .
    • you could give the code showing where $compname is set
    • you could give the code for your err sub
    You'll probably get a better answer.

(tye)Re: Simple length question
by tye (Sage) on Jan 28, 2002 at 23:20 UTC

    I'm not sure which reasons lead you to that design. The more common approach is something like:

    &err( "Too Few Characters in Company Login Name" ) if length($compname) < 6;
    or even
    $errmsg = "Too Few Characters in Company Login Name"; &err($errmsg) if (length($compname) < 6);
    where you code:
    sub err { my( $errmsg )= @_; # ... }
    rather than using a shared (probably global) variable. This might even fix the problem you are having as managing to get the variable properly shared can sometimes be tricky (I can't say since you didn't tell us what error you were getting).

    However, if you insist on not passing the error message to the "err" subroutine, you should at least do:

    $errmsg = "Too Few Characters in Company Login Name"; &err() if (length($compname) < 6);
    as &err w/o the parens is a special case that should usually be avoided. See (tye)Re: A question of style for more on that.

            - tye (but my friends call me "Tye")
Re: Simple length question
by n3dst4 (Scribe) on Jan 28, 2002 at 22:22 UTC
    Having no idea where $compname comes from, what err() does, or what $errmsg is for, it's kind of hard to help you here. This case works exactly as expected:

    sub foo { print "Foo!\n"; } my $string = 'completelycoveredinchocolate'; foo if (length($string) < 6);

    Your example is substantively different only in that we can't see what you've done with your string. So I reckon that's your problem. Try outputting it. Try outputting its length. It's a technique very broadly called 'instrumentation', and is the easiest way to debug small projects.