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

Hi

I apologize in advance for the stupid question. I've used 'split' to process a long text string into an array. Some of the array elements now look empty, but I suspect that they contain a newline character.

I want to test for the presence of this array element containing only a newline. I've tried this:

until ($discovered[$i] =~ "\n")
but it matches on every array element, since every array element contains a text string. How can I test for any array element that ONLY contain a single newline character?

Thanks tl

Edit by castaway - Added code tags

Replies are listed 'Best First'.
Re: Test for newline
by BUU (Prior) on Feb 19, 2005 at 08:16 UTC
    Look. If you want to test if a string is exactly equal to another string, use the "string equality operator" known as "eq", documented in perlop. $foo eq "\n"
Re: Test for newline
by gopalr (Priest) on Feb 19, 2005 at 06:58 UTC

    Use ^ and $

    It'll match only \n contains

    $discovered[$i] =~ "^\n$";
      This is not exactly the right thing, as /^\n$/ matches both "\n" and "\n\n". Use \z rather than $, or, better, use eq.
Re: Test for newline
by renz (Scribe) on Feb 19, 2005 at 06:53 UTC

    Something like this?

    #!/usr/bin/perl -w use strict; use warnings; my $element = 0; my @array = qw(one \n two \n three four \n five six); for (0 .. $#array) { if ($array[$element] =~ /\\n/) { print 'found newline in element ' . $element . "\n"; } $element++; }

    /renz.

Re: Test for newline
by saintmike (Vicar) on Feb 19, 2005 at 08:23 UTC
    You're using $discovered$i, which is isn't an array element, but an awkwardly constructed scalar variable name. You might want to look into using a real array instead.

    If you want to check if the value of a variable equals the newline character, just use $variable eq "\n" as a test, there's no need to use a regex.

    And, of course, $foo =~ "pattern" isn't a regular expression match. I'm not quite sure why it isn't a syntax error, but it's certainly wrong. $foo =~ /pattern/ is probably what you mean.

      While your first two points are correct, I'm afraid I must point out that your third point is incorrect.

      $foo =~ "pattern" is mostly certainly a regular expression match, with the expression "pattern" being applied to the variable $foo. The =~ operator will accept anything that may be stringified as it's right hand side, which is really what a regex is, // are just fancy quotes that have slightly different semantics.
        Interesting, thanks for pointing that out!

        I wouldn't recommend using $string =~ "...", though, it's confusing to beginners. Imagine if someone writes "\w" and wonders why it behaves differently than /\w/.

      He uses $discovered[$i], but because there are no code-tags the brackets are interpreted as a link.


      holli, /regexed monk/