in reply to Re: How can grep search based on text or pattern based on user input?
in thread How can grep search based on text or pattern based on user input?

First off, thanks all for your previous help.

OK, while I know a radio button would be easiest for this solution, I'm fairly confident that most of my users will just get confused. But I still want to offer the extra ability to those wise few. (Besides, this is a fun little learning project.) So I need to just do everything auto-magicly. If I can't remove the "/"s from the grep line, can I do something like:

grep /$searchtext/$modifiers @stuff

Problem is, I'm reasonably sure this will not work. I also am nervous about this not being able to handle any regex the highly-skilled user may input. Essentially, I'm looking at getting the following to work:

@stuff = ('This is some text.','This is more text.'); $stext = '/some/i'; ($null, $text, $mod) = split(/\//, $stext); foreach (grep /$text/$mod, @stuff) { print $_, "\n"; }

Can anyone get this to work? BTW, please tell me if I'm being an annoying-newbie, and I'll go away.

Replies are listed 'Best First'.
Re: Re: Re: How can grep search based on text or pattern based on user input?
by chromatic (Archbishop) on Dec 04, 2000 at 22:49 UTC
    Removing the slashes is pretty easy. Here's one (non-optimal) attempt:

    $input =~ s!^/(.+)/$!$1!;

    With that in place, everything you've described so far, except for the $modifiers, will work. You'd either have to escape everything and wrap the whole grep in an eval block, or use some sort of checkbox or if-else block to check for a case insensitive flag.

    Perl won't (as far as I know, and I'm pretty sure about this having just tested it) interpolate a variable in the regex flag position.

      However, Perl does provide the (?modifier) syntax, for putting the modifiers inside the regex: /(?i)abc/ So, to make this into a full example:
      @stuff = ('This is Some text.','This is More text.'); $stext = '/some/i'; ($null, $text, $mod) = split(/\//, $stext); if ($mod and $mod !~ /[^ism]/) { # a little sanity checking on the mo +difers $mod = "(?$mod)"; } else { $mod = ''; } foreach (grep /$mod$text/, @stuff) { print $_, "\n"; }
      Adjust the sanity checking on $mod however you like. BTW, Perl allows (?x) as well as (?ism), but I figured you wouldn't need that here.