Rob Dixon wrote:
Richard Lee wrote:
say I have

my $var1 = 'abcdefg';

my @array = ( 'abcdefg_3432', 'defg_333', 'abcdefg_' , 'abcdefg_a' );

Let's say I want to go through the array to see if $var1 exists and also to see if it followed by _ and then 4 digits (only first one should quailfy , abcdefg_3432 )

I tried,

for (@array) {
   next unless $_ =~ m#$var1_\d\d\d\d# ;

This is much more concisely written

  next unless /$var1_\d\d\d\d/;

   print "$_\n";
}


obviously this does not work.. so I tried

Why do you say 'obviously'. It can't be so obvious or you wouldn't have
tried it in the first place. What problem did you see? The code you
posted prints

  abcdefg_3432

Try it!

But there are several things wrong. First of all, always

  use strict;
  use warnings;

at the start of your program. That would stop the code above compiling
and would tell you what error you made. Perhaps you should try that now too.

If you tried it, it would have said

  Global symbol "$var1_" requires explicit package name

So it's including the trailing underscore as part of the variable's
name. But I suspect you already have a clue about this problem,
otherwise why write this

    next unless $_ =~ m#{$var1}_\d\d\d\d#;

which also didn't work(? should it have worked?)

Which is close, but as you say it didn't work.

If you'd used parentheses

  /($var1)_\d\d\d\d/

instead of braces you would have got the right result, but for the wrong
reasons.

Braces have several different special meanings throughout Perl, and
which meaning is in effect isn't always obvious. Within regular
expressions, a pair of braces can surround a quantifier ( /.{4}/ or
/a{1,5}/ ) or can be used to delimit the name of an interpolated
variable, which is what I guess you are trying to do here.

But the variable name doesn't include the $, % or @ at the beginning
(called the sigil) so what you need is

  /${var1}_\d\d\d\d/

how do you normally match through regex when you have to compare more than it's own variable?

You can build regexes and then print them to see if they do what you
want. For instance

  my $regex = qr/${var1}_\d\d\d\d/;
  print $regex, "\n";
  for (@array) {
    next unless $_ =~ $regex;
    print "$_\n";
  }

and errors like this will show up immediately.

HTH,

Rob
I need to study more on qr.. but ${ } definitely works for me.. thank you!

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to