http://qs321.pair.com?node_id=11113029


in reply to Find element in array

You have already been given the pieces you need, but they don't fit your hand and you haven't shown us what you have tried when you say "I still don't get it to work". The code below is a slightly more fully worked example using suggestions you have already been given:

use strict; use warnings; my $inputLines = <<LINES; TAAGAACAATAAGAACAA TAAGAACA.TAAGAACAA TAAG-ACA.TAAGAA_AA LINES open my $inFile, '<', \$inputLines or die "Can't open file: $!\n"; while (my $line = <$inFile>) { chomp $line; next if $line !~ /([^ACGT])/; print "In line $.: $line\n"; my $offset = 0; while ($line =~ /([^ACGT])/) { print "Found $1 at ", $-[1] + $offset, "\n"; substr $line, 0, $-[1] + 1, ''; $offset += $-[1] + 1; } }

Prints:

In line 2: TAAGAACA.TAAGAACAA Found . at 8 In line 3: TAAG-ACA.TAAGAA_AA Found - at 4 Found . at 8 Found _ at 15

This is a "Simple Self Contained Example". You can run the code without needing anything else. You should first copy this code (cut and paste is highly recommended) and check that it works yourself. Then play with it until you have some understanding of how it works. Then adapt it to you own needs.

There are some important things there. Note the use of strictures (use strict; use warnings;). Always use strictures in your code! The my $inputLines = <<LINES; and following lines create a variable initialised with multiple lines of text. That is used in open my $inFile, '<', \$inputLines or die "Can't open file: $!\n"; as a file. You can replace \$inputLines with a file name to open a file instead.

In while (my $line = <$inFile>) { you could instead use <STDIN> to read lines from the command line.

You are already using a regular expression so we assume you know something about those. If you don't, ask. The new bit is that $-[$n] gives the 0 based position (index) of the $n'th match.

substr is used to trim the line to the point of the matched character ready to find the next bad character.

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond