Category Archives: Perl

Perl in_array()

Perl can use the grep function as the equivalent of PHP’s in_array() function. ¬†Essentially

$found = grep $_ eq $my_value, @my_array

Note, the grep() function is world unto its own, it can do quite a bit more than just this. ¬†$found is actually $my_value if it finds it, which tends to evaluate to ‘True’ in Perl.

Perl str_replace

$s =~ s!\Q$search!$replacement!g;

\Q will quote a string until \E (if \E is ommitted will quote the whole string). You need to quote the string because s/// uses regexp;

You can view more Perl written in PHP here.

Perl – quick read text files scripts

These two Perl utility scripts are used to quickly read a text file into either a string or an array.

sub read_file_into_string {
  my $s = '';
  open FH, @_[0];
  for (<FH>) { $s .= $_; }
  close FH;
  return $s;
sub read_file_into_array {
  my @lines = ();
  open FH, @_[0];
  for (<FH>) {
    push @lines, $_;
  close FH;
  return @lines;