not pattern

Discussion in 'Perl Misc' started by MattJ83, Sep 13, 2006.

  1. MattJ83

    MattJ83 Guest

    Quick question
    if i was to write code to match a /pattern/ but then wanted the script
    to exit if it didn't find the pattern is it as simple as (!/pattern/) ?


    Code:
    {
    if (/word/)
    {
    print "$_\n";
    $info = $_;
    } elsif /!word/ { exit; } # ????

    Thanks
     
    MattJ83, Sep 13, 2006
    #1
    1. Advertisements

  2. MattJ83

    David Squire Guest

    Yes, but that is not what you have written below.
    First, you don't need an 'elsif', you just want an 'else' since your
    second test is (meant to be) just the negation of the first. Secondly,
    you need the ! (not) to be outside the pattern. Please try out your code
    before posting it.

    The example below illustrates these points.

    ----#!/usr/bin/perl

    use strict;
    use warnings;

    while (<DATA>) {
    print;
    if (!/g/) {
    print "\tNo 'g'\n";
    }
    else {
    print "\tContains 'g'\n";
    }
    }


    __DATA__
    cat
    dog
    frog
    bird

    ----

    Output:

    cat
    No 'g'
    dog
    Contains 'g'
    frog
    Contains 'g'
    bird
    No 'g'
     
    David Squire, Sep 13, 2006
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.