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

dear monks,

i'm trying to find a way to find a string which is situated between 2 string that i want to define..
after a reading on perlfaq i get an operator defining an interval: /exp1/../exp2/
so i tried this
#!/usr/bin/perl -w open(FICH, "a.txt"); while (<FICH>) { print if /string1/../string2/ ; } close FICH;
but as you imagine it give back all the text,could you help me to find how to turn the exp to discard the out range.

Thanks for your help.

Replies are listed 'Best First'.
Re: find a string into an interval
by shenme (Priest) on Sep 21, 2004 at 23:29 UTC
    Something else may be going wrong, as this works:
    #!/usr/bin/perl use strict; use warnings; while (<DATA>) { print if /string1/../string2/; } close DATA; 1; __DATA__ this is string0 line and this is string1 line this might be string1a line and this line has string2 to finish, string3 line ends it all
    produces output
     and this is string1 line
     this might be string1a line
         and this line has string2
    
    Note that sometimes people use the __DATA__ feature to show file I/O related code. Please don't let that confuse you.
Re: find a string into an interval
by tachyon (Chancellor) on Sep 21, 2004 at 23:45 UTC

    You may be looking for something like this (if you only want data literally between the strings). Note the /s allows . to match newlines.

    #!/usr/bin/perl local $/; # undef input record separator my $str = <DATA>; # get all file DATA into string my @matches = $str =~ m!str1(.*?)str2!gs; print @matches; __DATA__ str1 Hello str2 str1 World str2 str1 ! str2

    cheers

    tachyon

Re: find a string into an interval
by ikegami (Patriarch) on Sep 21, 2004 at 23:40 UTC

    I'm not sure what you want. If shenme's reply doesn't help, this might:

    while (<DATA>) { print if (/string1/../string2/) && /string3/; # Only prints "string3 2" } __DATA__ bla bla string3 1 foo foo string1 bar bar string3 2 bah bah string2 feh feh string3 3 moo moo
Re: find a string into an interval
by TedPride (Priest) on Sep 22, 2004 at 08:20 UTC
    Assuming your file is large and has to be read line by line, and assuming there may be more than one line with a match:
    #!/usr/bin/perl -w $s1 = 'exp1'; $s2 = 'exp2'; open(FICH, "a.txt"); while (<FICH>) { if ($_ =~ /$s1(.*?)$s2/) { print "$1\n"; } } close FICH;