Home: Perl Programming Help: Regular Expressions:
Count name! Help me!



thesun
Novice

May 15, 2011, 10:28 AM


Views: 7856
Count name! Help me!

I' ve a problem about counting name in a string.
Name has format {#name} such as {#john} or {#mr_peter}... A name include lowercase character, digits or underline "_" character is valid.

And, enter a paragraph, how many name in this.
Exam:
Input: {#john} and {#conankudo} play PES with {#mr_invincible}. { {#john} win {###} {
Output:
4
because have 4 name is: {#john}, {#conankudo}, {#mr_invincible} and {#john}.

Who can help me! please.


BillKSmith
Veteran

May 15, 2011, 5:29 PM


Views: 7847
Re: [thesun] Count name! Help me!


Code
use strict; 
use warnings;
my $paragraph =
'{#john} and {#conankudo} play PES with {#mr_invincible}. { {#john} win {###} {'
;
print "Input: " . $paragraph . "\n";
(my @names) = $paragraph =~ m/(\{#[a-z_0=9]+\})/g;
print "Output: " , scalar @names, "\n";

Good Luck,
Bill


shawnhcorey
Enthusiast


May 15, 2011, 6:41 PM


Views: 7845
Re: [BillKSmith] Count name! Help me!


In Reply To

Code
(my @names) = $paragraph =~ m/(\{#[a-z_0=9]+\})/g;



Make that second equal sign a minus:

Code
(my @names) = $paragraph =~ m/(\{#[a-z_0-9]+\})/g;


__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


thesun
Novice

May 15, 2011, 7:51 PM


Views: 7842
Re: Count name! Help me!

thanks everyone.
I want to enter paragraph in multiline.
It is my code:

Code
$a=0; 
while($para=<>){
@name=$para=~ m/(\{#[a-z_0=9]+\})/g;
$a+=scalar@name;
if(eof){print $a,"\n";}
}

But it not stop. I don't understands


BillKSmith
Veteran

May 16, 2011, 6:14 AM


Views: 7824
Re: [thesun] Count name! Help me!

Not only is your test of eof unnecessary, it probably does not do what you think (Refer perldoc -f eof).

You must correct my typo as Shawn pointed out.

This program will accept input from STDIN (usually the keyboard) until it reads an end-of-file. The way you type an end-of-file depends on your operating system. (For windows, use CTRL-Z followed by ENTER.)

Although it has nothing to do with you current problem, you should always use the pragmas "use strict" and "use warnings". This will force you to declare all your variables (almost always with "my").
Good Luck,
Bill