CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Problem

 



yaroba
Novice

May 26, 2013, 12:00 PM

Post #1 of 8 (574 views)
Problem Can't Post

Hello,

I have a task that sounds this: You have real and natural numbers in .txt file and you have to put every element in between <> brackets. Can anyone help me?


g4143
Novice

May 26, 2013, 1:40 PM

Post #2 of 8 (567 views)
Re: [yaroba] Problem [In reply to] Can't Post

Can you give us an example of the text file?


yaroba
Novice

May 26, 2013, 1:55 PM

Post #3 of 8 (564 views)
Re: [g4143] Problem [In reply to] Can't Post

the .txt file should look like this : 23530-2-5


Laurent_R
Veteran / Moderator

May 26, 2013, 2:17 PM

Post #4 of 8 (562 views)
Re: [yaroba] Problem [In reply to] Can't Post

And how is your output supposed to look?


Code
<23530>-<2>-<5>


or


Code
<23530-2-5>


Adssuming the first answer, the following session under the Perl debugger gives a possible solution:


Code
  DB<14> $n = "23530-2-5"; 

DB<15> $n =~ s/(\d+)/<$1>/g;

DB<16> print $n;
<23530>-<2>-<5>



yaroba
Novice

May 26, 2013, 2:34 PM

Post #5 of 8 (560 views)
Re: [Laurent_R] Problem [In reply to] Can't Post

My bad, it should take one number after another and put it in the brackets. 2,3,5,3,0,-2,-5 should be converted to <2>, <3>, <5> and etc.


(This post was edited by yaroba on May 26, 2013, 2:58 PM)


BillKSmith
Veteran

May 26, 2013, 3:28 PM

Post #6 of 8 (552 views)
Re: [yaroba] Problem [In reply to] Can't Post


Code
use strict; 
use warnings;
my $string = <DATA>;
$string =~ s/([-+.\d]+)/<$1>/g;
print $string;
__DATA__
2,3,5,3,0,-2,-5


OUTPUT:

Code
<2>,<3>,<5>,<3>,<0>,<-2>,<-5>

Good Luck,
Bill


yaroba
Novice

May 26, 2013, 4:22 PM

Post #7 of 8 (547 views)
Re: [BillKSmith] Problem [In reply to] Can't Post

Thanks once again for your help :)

I have one more question, what is wrong with my code?

use strict;
use warnings;

my $string = '';

open my $FILE, '<', 'numbers.txt' or die;

while (<$FILE>) {
$string =~ s/([-+.\d]+)/<$1>/g;
print "$string\n";
}


BillKSmith
Veteran

May 26, 2013, 7:41 PM

Post #8 of 8 (536 views)
Re: [yaroba] Problem [In reply to] Can't Post

You are reading the file into $_, not $string.

Code
use strict; 
use warnings;
open my $FILE, '<', 'numbers.txt' or die "Cannot open numbers.txt:$!";
#######while (<$FILE>) {
while ( my $string = <$FILE> ) {
$string =~ s/([-+.\d]+)/<$1>/g;
print "$string\n";
}

Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives