lola
lola

Reputation: 5799

How to use "or " operator to assign several values to a variable?

I'm new with perl.

I would like to say that a variable could take 2 values, then I call it from another function.

I tried:

  my(@file) = <${dirname}/*.txt || ${dirname}/*.xml> ;

but this seems not working for the second value, any suggestions?

Upvotes: 2

Views: 163

Answers (5)

Zaid
Zaid

Reputation: 37156

If I understood correctly, you want @files to fallback on the second option (*.xml) if no *.txt files are found.

If so, your syntax is close. It should be:

my @files = <$dirname/*.txt> || <$dirname/*.xml>;

or

my @files = glob( "$dirname/*.txt" ) || glob( "$dirname/*.xml" );

Also, it's a good idea to check for @files to make sure it's populated (what if you don't have any *.txt or *.xml?)

warn 'No @files' unless @files;

Upvotes: 1

amon
amon

Reputation: 57656

When using the <*> operator as a fileglob operator, you can use any common glob pattern. Available patterns are

  • * (any number of any characters),
  • ? (any single character),
  • {a,b,c} (any of the a, b or c patterns),

So you could do

my @file = glob "$dirname/*.{txt,xml}";

or

my @file = (glob("$dirname/*.txt"), glob("$dirname/*.xml"));

or

my @file = glob "$dirname/*.txt $dirname/*.xml";

as the glob pattern is split at whitespace into subpatterns

Upvotes: 6

Vorsprung
Vorsprung

Reputation: 34457

This works

my $file = $val1 || $val2;

what it means is set $file to $val1, but if $val1 is 0 or false or undef then set $file1 to $val2

In essence, surrounding a variable with < > means either

1) treat it as a filehandle ( for example $read=<$filehandle> )

2) use it as a shell glob (for example @files=<*.xml> )

Looks to me like you wish to interpolate the value $dirname and add either .txt or .xml on the end. The < > will not achieve this

If you wish to send two values to a function then this might be what you want

my @file=("$dirname.txt","$dirname.xml");

then call the function with @file, ie myfunction(@file)

In the function

sub myfunction {
  my $file1=shift;
  my $file2=shift;

All this stuff is covered in perldocs perlsub and perldata

Have fun

Upvotes: 0

arunxls
arunxls

Reputation: 124

my(@file) = <${dirname}/*.txt>, <${dirname}/*.xml> ;

<> converts it into an array of file names, so you are essentially doing my @file = @array1, @array2. This will iterate first through txt files and then through xml files.

Upvotes: 0

Barmar
Barmar

Reputation: 782775

my (@file) = (<${dirname}/*.txt>, <${dirname}/*.xml>);

Upvotes: 0

Related Questions