Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Simple regexp question

by l.frankline (Hermit)
on Mar 31, 2006 at 04:11 UTC ( #540361=note: print w/replies, xml ) Need Help??

in reply to Simple regexp question


I couldn't understand your expectation. If my guess is right, then try the following:

open INFILE,"$filename" || die "cant open the input file";
while (<INFILE>) {
    push (@filtered,$_) if (/[\#\*]+/);
print "@filtered";


Don't put off till tomorrow, what you can do today.

Replies are listed 'Best First'.
Re^2: Simple regexp question
by ikegami (Patriarch) on Mar 31, 2006 at 04:28 UTC
    • "$filename"
      doesn't need to be in quotes.
      will do fine.

    • open INFILE, '<', $filename
      is less error-prone and safer than the two-arg version.

    • It's good to use local variables for file handles. Replace
      open INFILE, '<', $filename
      open local *INFILE, '<', $filename
      open my $fh_in, '<', $filename

    • open local *INFILE, '<', $filename || die "cant open the input file";
      is the same as
      open local *INFILE, '<', ($filename || die "cant open the input file");
      which is definitely not what you want. Use
      open(local *INFILE, '<', $filename) || die("Unable to open the input file: $!\n");
      open local *INFILE, '<', $filename or die "Unable to open the input file: $!\n";

    • We don't need to know how many # and * we have in a row, so
      if (/[\#\*]+/)
      can be simplified to
      if (/[\#\*]/)
      And since # and * are not special in character class, you don't need to escape them. The following in sufficient.
      if (/[#*]/)
      Also, the parens are optional on a if suffix, and just add clutter in this case. I'd remove them as follows:
      if /[#*]/

    • I think "to filter out lines" means "to remove lines". If so, replace
      if /[#*]/
      unless /[#*]/

    • Your print is adding spaces. Replace
      print "@filtered";
      print @filtered;

    We get the following:

    open(local *INFILE, '<', $filename) or die("Unable to open the input file: $!\n"); my @filtered; while (<INFILE>) { push(@filtered, $_) unless /[#*]/; } print @filtered;

    What follows is a more elegant but more memory intensive alternative:

    open(local *INFILE, '<', $filename) or die("Unable to open the input file: $!\n"); my @filtered = grep { !/[#*]/ } <INFILE>; print @filtered;
    A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://540361]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2023-05-31 15:50 GMT
Find Nodes?
    Voting Booth?

    No recent polls found