in reply to Print the output results of matching line horizontally
Modify my DATA section below with the correct formatting.
I made some assumptions about what the data looked like. I took out all of these chomp() statements as they are not necessary. Note that .* in a regex matches all characters except new line's. Also note that chomp @lines; is actually a foreach loop - don't do that if you are going to process each line individually again.
I just made a small change to your print statement. I would have some other suggestions for you, but let's get the problem statement completely defined first. Your code although somewhat awkward basically "works".#!/usr/bin/perl use strict; use warnings; my ($sname,$result); #my $cmd ="results.bat"; my @lines = <DATA>; #print "@lines\n"; #chomp (@lines); foreach my $line(@lines){ # chomp ($line); if ($line =~ m/Student\sName\s+=\s(.*)/i){ # chomp ($1); $sname =$1; print "$sname "; #changed } if ($line =~ m/Exam\sStatus\s+=\s(.*)/i){ # chomp ($1); $result =$1; print "$result "; #changed } } print "\n"; =Prints: Harry PASSED Mike PASSED Tom PASSED =cut __DATA__ Student Name = Harry Student Code = student_id_1 Exam Status = PASSED ------------------------------------- Student Name = Mike Student Code = student_id_2 Exam Status = PASSED ------------------------------------- Student Name = Tom Student Code = student_id_3 Exam Status = PASSED -------------------------------------
Update:
I noticed that my DATA segment has some trailing spaces. That is probably not true of your actual input file. However a slight regex modification can handle this situation - a "minimal match" upon (.*) that allows for trailing blanks to be deleted. Here is some code for your consideration...
I can tell that you are very new to Perl. That is fine. And this is a good place to go. There is a limit to what can be conveyed in a single thread. If you read and learn more about chomp then I consider this instructional exercise a success.#!/usr/bin/perl use strict; use warnings; while (my $line = <DATA>) { print "$1 " if $line =~ m/Student Name\s*=\s*(.*?)\s*$/; #deletes t +railing spaces print "$1 " if $line =~ m/Exam Status\s*=\s*(.*?)\s*$/; #deletes t +railing spaces } print "\n"; =Prints: Harry PASSED Mike PASSED Tom PASSED Bob Smith FAILED =cut __DATA__ Student Name = Harry Student Code = student_id_1 Exam Status = PASSED ------------------------------------- Student Name = Mike Student Code = student_id_2 Exam Status = PASSED ------------------------------------- Student Name = Tom Student Code = student_id_3 Exam Status = PASSED ------------------------------------- Student Name = Bob Smith Student Code = student_id_4 Exam Status=FAILED
|
|---|