Murali Newbee:
When teaching someone programming, I generally try to get them to write down what they want, then ask them a few questions to get them to state what they want in the simplest form possible. Once you go through that exercise a few times, you'll find it easier to do the whole process in your head.
It seems you've provided enough information, so I'll show you an imaginary dialog:
MN: I'm trying to get a numeric ID into a variable.
Robo: OK, if that's the only number on the line, you could try something like:
if ($var =~ /(\d+)/) { $ID = $1 }
Robo: Is it the only number on the line?
MN: No, there could be numbers in several places.
Robo: OK, then, how can you tell the ID from the other numbers:
- Is it the first (or second, third, ..., last) one on the line?
- Does it have a particular number of digits?
- Does it have a particular suffix or prefix?
- Is it something else I haven't come up with?
MN: It's always got "eid-" or "eid -" or "eid - " before it.
Robo: OK, then you'll want a regular expression to look for "eid", some optional spaces, a hyphen, perhaps some more spaces and then a number, right?
MN: Yeah, that sounds about right.
Robo: OK, then, you'll want something like:
$ cat t.pl
use strict;
use warnings;
my @examples = (
'Something something -something1 something eid- 1234 gkn 12-34_loa
+nmaster',
'Something :something something6 eid - 4532 gkn 34-21-hostmasfer',
'eid 762 something something1 something@',
);
for my $v (@examples) {
if ($v =~ /
eid # Prefix for the ID
\s* # might have some spaces
(-\s*)? # maybe a hyphen with more spaces
(\d+) # has one or more digits
/x) {
print "Found ID <$2> in <$v>\n";
}
}
$ perl t.pl
Found ID <1234> in <Something something -something1 something eid- 123
+4 gkn 12-34_loanmaster>
Found ID <4532> in <Something :something something6 eid - 4532 gkn 34-
+21-hostmasfer>
Found ID <762> in <eid 762 something something1 something@>
I frequently find the process of coding to be breaking a problem down into smaller and smaller pieces. Once each piece is small enough, state the problem clearly enough to make it straightforward. From there, convert it into code. As you gain experience in programming, you'll find it easier and easier to do most of the process in your head and just write down the code, as it seems QM, haj and anonymized user 468275, did for you.
Update: I didn't mean to slight the other respondents, I'm just having a slow morning today.
...roboticus
When your only tool is a hammer, all problems look like your thumb. |