help with perl

Hi,

I have a set of files where one of the lines in each file will have a <cd> tag in it when i grep for it. It may be in two formats,

  1. </ab><cd>35250</cd>
  2. <cd>35250</cd>

However it may be, i need to get the number value between <cd>" "</cd>.

Hope i am clear on my question, I am writing a perl script, i have used substr and index commands, but did not work for me, if anyone has any suggestions i appreciate it.

Thanks--

if (m%<cd>(.*?)</cd>%) { $stuff = $1 }

... provided the start and end tags are always on the same line. If there can be multiple occurrences on the same line, you need to add a loop and a /g flag, too.

Thanks era, yes they are always in the same line. Can you please explain me what exactly is it doing?
as far as my understanding goes - (.?) this is fetching the all the values in between the tags .. what does the m% do? and is $1 output from the if condition?
if (m%<cd>(.
?)</cd>%) { $stuff = $1 }

thanks again for you quick reply:)

m%....% is a regular expression match; you'd normally see /.../ or m/.../ but we don't want to use slashes when the pattern itself contains slashes.

If there is a match, the part of the string which matched the parenthesized part of the regular expression will be in $1.

Thanks for you reply era. THis is the code i am using to fetch the number value in between <cd>????</cd> .. but this is the case when this tag is in the same way in all files .. but when </ab><cd>????</cd> this is the case where this will not be able to handle ..
i am little confused about how to fit in ur code here .. can you help me on this .. i really appreciate it.. Thanks--

foreach my $file (@array_files){
open(fh,">>","tmp.out");
# if (m%<cd>(.*?)</cd>%) { $stuff = $1 }
print fh `tail $file|grep "^<cd>"|grep "</cd>"| cut -d"<" -f 2|cut -c 4-`;
close fh;
}

What's the point of using Perl if the one thing Perl can do really well is handled by a shell function?

#!/usr/bin/perl -n
if (m%<cd>(.*?)</cd>% { print "$1\n" }

Save that to a file and run it from a shell script which invokes it on each file in turn. Or just type this one-liner directly at the prompt.

perl -ne 'if (m%<cd>(.*?)</cd>%) { print "$1\n" }' *.txt >tmp.out

Thanks era, the one liner helps! :slight_smile: