LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   perl script (https://www.linuxquestions.org/questions/linux-general-1/perl-script-459275/)

jazman 06-28-2006 07:07 PM

perl script
 
I have this perl code:

my($line) = $_;
chomp($line);
$line =~ tr/[a-z]/[A-Z]/;

I need to test if the first two character of a line in a text file "2:"

What would I use to test such a condition?

gilead 06-28-2006 07:21 PM

The following just loops through a file and checks whether each line starts with 2: - is that all you wanted it to do?

Code:

open( REPORT, "afile.txt" ) || die "Can't open afile.txt: $!\n";
while ( $line = <REPORT> ) {
  if ( $line =~ m/^2:/ ) {
    print "It matches!\n";
  }
}
close( REPORT ) || die "Can't close afile.txt: $!\n";


jazman 06-28-2006 07:22 PM

perfect
 
Thats great thanks

jazman 06-28-2006 07:30 PM

One last thing
 
What I need to get is

2:06/06/07 15:49 is my $line

is the complete string... I want to test for just the first 2:

if ( $line =~ m/^2:/ )

Will this do that? or do I need to break it down to the first two characters?

gilead 06-28-2006 08:08 PM

I might not be understanding you properly, but...

$line =~ m/^2:/ will test the first 2 characters of $line and does not change $line. If you use $line after matching, it will have the same value as it had before matching. So if $line was 2:06/06/07 15:49 before the match, it is still 2:06/06/07 15:49 after the match.

If you want to know what happens during a match, perl sets several variables you can use after the match statement. Perl sets $` to the string preceding the match, it sets $& to the string that was matched and it sets $' to the string following what was matched. For the example of 2:06/06/07 15:49 this is what they would be:
Code:

$` would be the empty string at the start of the line
$& would be 2:
$' would be 06/06/07 15:49
$line would be 2:06/06/07 15:49

Using these variables can cause a performance hit, so test them if you want to use them with large files.

Hope that helps...


All times are GMT -5. The time now is 07:17 PM.