if the directory you want to find is known beforehand.
$str = "blah blah cd /a/b/c blah";
if ( $str =~ /cd \/a\/b\/c/ ){
print "found\n";
chdir("/a/b/c");
}
ghostdog74
2010-03-29 16:41:28
if the directory you want to find is known beforehand.
$str = "blah blah cd /a/b/c blah";
if ( $str =~ /cd \/a\/b\/c/ ){
print "found\n";
chdir("/a/b/c");
}
#!/usr/bin/perl
use strict; use warnings;
while ( my $line = <DATA> ) {
if ( my ($path) = $line =~ m{^cd \s+ (/? (\w+) (?:/\w+)* )}x ) {
warn "Path is $path\n";
chdir $path
or warn "Cannot chdir to '$path': $!";
}
}
__DATA__
cd a
cd /a/b/c
cd /a
Output:
Path is a Cannot chdir to 'a': No such file or directory at C:\Temp\k.pl line 8, line 1. Path is /a/b/c Cannot chdir to '/a/b/c': No such file or directory at C:\Temp\k.pl line 8, line 2. Path is /a Cannot chdir to '/a': No such file or directory at C:\Temp\k.pl line 8, line 3.
What you really want is a dispatch table. When you encounter a command, like cd
, you look up an associated subroutine in the dispatch table where you map valid commands to the code that you want to run:
%dispatch = ( cd => sub { chdir( $_[0] ) }, ... ); while( <> ) { my( $command, @args ) = split; if( exists $dispatch{ $command } ) { $dispatch{ $command }->(@args); } }
I have several extended examples of this sort of thing in Mastering Perl. The nice bit about this is that you don't change the processing loop when you have new commands, and you only handle the commands you intend to handle. Furthermore, you can construct that dispatch table directly from configuration.