put perl command within if-else

J

Jie

Hi,

I want to process a list. However, this list could exist as a provided
file, or in a hash created. I am thinking to use the following code,
first to find if this list exists in a file or in a hash, but this
code does NOT work.... Do I need to put "do something here" into a
function and then call this function? I am not very comfortable with
function though...

Your insight is appreciated!

jie

==============my piece of code==========
if ($list_file) {
open (LIST, "< $list_file") or die "Can't open file";
while (<LIST>) {
} else { ## this list is in a hash created previously
foreach $key (%LIST_HASH) {
}

!!!!do something here!!!;
}
 
P

Paul Lalli

I want to process a list. However, this list could exist as a
provided file, or in a hash created. I am thinking to use the
following code, first to find if this list exists in a file or
in a hash, but this code does NOT work.... Do I need to put "do
something here" into a function and then call this function?
I am not very comfortable with function though...
==============my piece of code==========
if ($list_file) {
open (LIST, "< $list_file") or die "Can't open file";
while (<LIST>) {} else { ## this list is in a hash created previously

foreach $key (%LIST_HASH) {

You meant:
foreach my $key (keys %LIST_HASH) {

otherwise, you're iterating over both the keys and the values
}

!!!!do something here!!!;
}


What you want is not possible. You cannot intersperce a while or
foreach loop within the if statement. All blocks must fully nest.
That is, one block cannot end until all blocks started within it have
ended.

So, yes, the best way to handle what you want is to create a
subroutine and call that subroutine twice, once in the while loop,
once in the foreach.

For example:
if ($list_file) {
open my $LIST, '<', $list_file or die "Can't open $list_file: $!";
while (my $line = <$LIST>) {
chomp $line;
process($line);
}
} else { ## this list is in a hash created previously
foreach my $key (keys %LIST_HASH) {
process($key);
}
}

sub process {
my $item = shift;
#do whatever you want with the hash key or file line
print "Item: $item\n";
}


If, as you say, you are not comfortable with subroutines, you should
read:
perldoc perlsub

Paul Lalli
 
J

Jie

Thank you very much, Paul! I just learned from you that "shift" is one
to get a passed parameter!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,781
Messages
2,569,615
Members
45,297
Latest member
EngineerD

Latest Threads

Top