Perl in_array
PHP has a great function called in_array that allows you to test a value against an array to see if the value is in the array, returning TRUE or FALSE depending. I've now had to come up with this same thing in Perl a couple of times so I figured I would share. I can't remember where I found help or I'd reference them. But here you go. I've included both a syntax highlighted screenshot and the plain text to copy and paste.


my @states = ('California', 'Nevada', 'Texas', 'Utah');
my $findme = 'Utah';
if (in_array($findme, \@states)) {
print "Found it!";
} else {
print "Not found.";
}
sub in_array {
my ($item, $array) = @_;
my %hash = map { $_ => 1 } @$array;
if ($hash{$item}) { return 1; } else { return 0; }
}
Tagged as array, function, in_array, perl, php
Posted in Perl Programming
FIND and CHMOD Together
Getting directory and file permissions just right on Linux can be tricky because directories compared to files have different settings. This makes it so that a general, recursive chmod command will not work. This is where the power of using both 'find' and 'chmod' together comes in handy.
The above two commands do the following:
1. Search in the current directory represented by the dot.
2. Look for the files or directories, respectively.
3. They execute the chmod command when they find it.
That's a really simplified example, but hopefully it helps out.
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
The above two commands do the following:
1. Search in the current directory represented by the dot.
find .
2. Look for the files or directories, respectively.
-type f
-type d
3. They execute the chmod command when they find it.
-exec chmod 644 {} \;
-exec chmod 755 {} \;
That's a really simplified example, but hopefully it helps out.
Tagged as chmod, command line, find, linux, permissions
Posted in Linux Command Line