Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: Pattern matching in perl

by Anonymous Monk
on Jul 01, 2022 at 15:11 UTC ( #11145223=note: print w/replies, xml ) Need Help??

in reply to Pattern matching in perl

Because this is Perl, There Is More Than One Way To Do It:

use strict;
use warnings;

my $file = "/home/test.txt";

# Store the list of desired names in a hash, with a true value for each.
my %list = map { $_ => 1 } qw{ Anls core route };

open my $fh, '<', $file or die "Failed to open $file: $!";
while ( <$fh> ) {

  # Use split() to break $_ on slashes. Save only first two parts.
  my ( $x, $version ) = split /\//;

  # Print if hash entry {$x} contains a true value. Non-existing entries are false.
  print "$x: version $version\n" if $list{$x};
close $fh;

Replies are listed 'Best First'.
Re^2: Pattern matching in perl
by Fletch (Bishop) on Jul 01, 2022 at 15:18 UTC

    More portable to use File::Spec and splitpath rather than hardcoding a platform dependent separator . . .</nitpick>

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      Good point. I assumed that in this case the '/' was the chosen field delimiter in the input file, but all the OP said was (paraphrased) "I have a file that looks like this ...". If the input file actually contains file names, yours is the way to go unless we know they are POSIX-format names.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11145223]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2022-08-16 03:45 GMT
Find Nodes?
    Voting Booth?

    No recent polls found