• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 162
  • Last Modified:

Perl code to read from a file

Hello, I have a small stats project to work on.

I am learning perl, but have to learn it in a very short space of time.

Could anyone help me with some code, which would open a text file, draw out 7 comma delineated numbers, ie, 34,56,76,12,1,69,64 and insert them as individual entities into scalar variables ?

thanks

Mick
0
Europa MacDonald
Asked:
Europa MacDonald
  • 4
  • 3
1 Solution
 
mrjoltcolaCommented:
Here is one way.
#!/usr/bin/perl
 
open(IN, "<test.txt") or die;
 
my $s;
 
while($s = <IN>) {
   if($s =~ /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/) {
      my ($n1, $n2, $n3, $n4, $n5, $n6, $n7) = ($1, $2, $3, $4, $5, $6, $7);
      print "n1 = $n1,  n7 = $n7\n";
   }
}

Open in new window

0
 
Europa MacDonaldChief slayer of dragonsAuthor Commented:
thankyou
0
 
Europa MacDonaldChief slayer of dragonsAuthor Commented:
it doesn't print to the command line screen, should it ?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
mrjoltcolaCommented:
You are welcome.

Also look at the "split" function, you can split comma separated lines easily with it. I often prefer an explicit regular expression,


my @nums = split /,/, "1,2,3,4,5,6,7"

#!/usr/bin/perl
 
open(IN, "<test.txt") or die;
 
my $s;
 
while($s = <IN>) {
   my @nums = split /,/, $s;
   foreach (@nums) {
      print "$_\n";
   }
}

Open in new window

0
 
mrjoltcolaCommented:
>>it doesn't print to the command line screen, should it ?

Yes, with the test data I used. I made a file test.txt with one line of text:  34,56,76,12,1,69,64

0
 
Europa MacDonaldChief slayer of dragonsAuthor Commented:
I am using windows, should this make a difference ?
0
 
Europa MacDonaldChief slayer of dragonsAuthor Commented:
I apologise, it did that time.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now