How to properly declare global variables in Perl?

perl

Solution

`use vars qw()` Is not recommended any more. To declare a global variable use `our $my_var` Your problem may be comes from the condition `$cell->value() =~ /Site Name/` . It is probably never met so your variable never gets a value.

Problem

I am trying to understand variable scope and properly declaring variables in Perl, and I am having a hard time. The code below basically reads in an excel file, parses it, and spits it out to a new excel file. However, I am trying to read one of the headers, and if the header matches my string, I want to record that column number, and use it later in the code. I am getting a "Use of uninitialized value $site_name_col in print at ./parser.pl line 38." Line 38 is "print $site_name_col;" I realize this print statement is outside the {} where the variable was initially initialized, but it was declared as a global variable at the beginning of the code, so what gives? ``` #!/usr/bin/perl -w use strict; use warnings; use vars qw($site_name_col); use Spreadsheet::WriteExcel; use Spreadsheet::ParseExcel; my ($fname1) = @ARGV; my $parser = Spreadsheet::ParseExcel->new(); my $workbook = $parser->parse($fname1); my $new_workbook = Spreadsheet::WriteExcel->new('formated_list.xls', $fname1); if (!defined $workbook) { die $parser->error(), ".\n"; } for my $worksheet ( $workbook->worksheets() ) { my ($wsheet_name) = $worksheet->get_name(); my $new_worksheet = $new_workbook->add_worksheet($wsheet_name); my ($row_min, $row_max) = $worksheet->row_range(); my ($col_min, $col_max) = $worksheet->col_range(); for my $row ($row_min .. $row_max) { for my $col ($col_min .. $col_max) { my $cell = $worksheet->get_cell($row, $col); next unless $cell; print "Row, Col = ($row, $col)\n"; if ( $cell->value() =~ /Site Name/ ) { $site_name_col = $col; } print $site_name_col; $new_worksheet->write($row, $col, $cell->value()); } } } $new_workbook->close(); ```

Original source