Eren
Eren

Reputation: 21

Perl string comparison in text file

I am writing an abstract instruction file to be processed by a Perl script. Every line is of the format - "instruction operand1 operand2 ..."

So if I have one like - "copy dest src", I want to first check if the first word of the line says "copy" or not and proceed accordingly. How to do this using Perl?

Upvotes: 0

Views: 106

Answers (3)

Dave Cross
Dave Cross

Reputation: 69274

I'd use a dispatch table. Something like this:

# Define a subroutine for each of your commands

sub my_copy {
  my ($source, $dest) = @_;
  # other stuff
}

# Set up a hash where the keys are the names of the
# commands and the values are references to the
# subroutines

my %commands = (
  copy => \&my_copy,
  # other commands here
);

# Then, in the main processing section...

my ($cmd, @params) = split /\s+/, $input_line;

if (exists $commands{$cmd}) {
  # execute the subroutine
  $commands{$cmd}->(@params);
} else {
  warn "'$cmd' is not a valid command.\n";
}

Upvotes: 1

Timur Shtatland
Timur Shtatland

Reputation: 12347

This can be done without regexes if needed. Split on the whitespace and check whether the first word is equal to "copy", for example:

echo 'copy foo bar\nbaz' | perl -lane 'print if $F[0] eq q{copy};'

Output:

copy foo bar

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
-a : Split $_ into array @F on whitespace or on the regex specified in -F option.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches

Upvotes: 3

lordadmira
lordadmira

Reputation: 1832

You should start by reading up on the Perl documentation. What you're asking is very trivial.

https://perldoc.perl.org/perl#Tutorials

Here is a very brief example to get you started.

while (my $line = <$FILE_HANDLE>) {
  if ($line =~ m/^copy\b/) {
    # do something
  }
}

Read the regex tutorial (https://perldoc.perl.org/perlretut) to see how m// works. Everything you need is on that site.

Good luck.

Upvotes: 1

Related Questions