tags:

views:

92

answers:

5
$ cat names
projectname_flag_jantemp
projectname_flag_febtemp
projectname_flag_marchtemp
projectname_flag_mondaytemp
$

Perl code:

my $infile = "names";
open my $fpi, '<', $infile or die "$!";
while (<$fpi>) {
    my $temp = # what should come here? #
    func($temp);
}

I want temp to have

jan
feb
march
monday

respectively.

The pattern always remains the same

projectname_flag_<>temp

How should I do the extraction?

+1  A: 
while (<$fpi>) {
        chomp;
        s{projectname_flag_(.*?)temp}{$1};
        # $_ will now have jan, feb, ...
}
codaddict
How can I make this operate on a variable instead of `$_`? For example, input is in `$inp` instead of `$_` and output should also go to `$out` not `$_`?
Lazer
@Lazer: `( $out = $inp ) =~ s{projectname_flag_(.*?)temp}{$1};`
Alan Haggai Alavi
Or, use the new `/r` flag: http://www.effectiveperlprogramming.com/blog/659 ;-)
Sinan Ünür
A: 

I guess:

/^projectname_flag_([a-z]+)temp$/
SilentGhost
+7  A: 
my ($temp) = /^projectname_flag_(.+)temp$/;

Note that the parentheses around $temp are needed so that the pattern match runs in list context. Without them, $temp would end up containing just a true or false value indicating whether the match succeeded.

More generally, a pattern match in list context returns the captured subpatterns (or an empty list if the match fails). For example:

my $str = 'foo 123   456 bar';
my ($i, $j) = $str =~ /(\d+) +(\d+)/;  # $i==123  $j==456
FM
Just remember to check if the match succeeded.
Sinan Ünür
A: 

Hi, you could try this.

while (<$fpi>) {
  my ($temp) =($_ =~ m/projectname_flag_(.*?)temp/);
  func($temp);
}
racke
+1 for non-greedy
Axeman
-1 for using `.*` when `.+` (or a more restrictive pattern) would have been more appropriate.
Sinan Ünür
+7  A: 

If compatibility with older perls is needed, I would use FM's answer (just make sure the match succeeded by checking if $month is defined).

As of 5.10, you can use named captures:

my $month;
if ( /^ projectname _flag_ (?<month> [a-z]+ ) temp \z/x ) {
    $month = $+{month};
}
Sinan Ünür
Thanks, I did not know about named captures.
Lazer