I am trying to use a subroutine to splice
an array. What am I doing wrong?
$foo = 123223;
@data = split(//, $foo);
splice_data(\@data);
printf(@data);
sub splice_data{
splice(@data,3,1,1);
return @data;
}
Output: 1
Expected output: 123123
CodePudding user response:
The code in the question has multiple serious issues
Data is passed to the sub but the sub doesn't read that
Sub directly uses data that happens to be seen in its scope
Sub is passed a reference, seemingly to use to change data in the caller, but returns a flat list of that data
Instead, we generally want a sub to have a clearly defined input, read via @_. It can return its results by directly changing data in the caller by writing to it using data reference(s) passed to it, if that is passed to it, or by explicitly return
-ing data (or both)
use warnings;
use strict;
use feature 'say';
sub splice_data {
my ($ref_to_data) = @_;
splice @$ref_to_data, 3, 1, 1;
return 1; # for "success"
}
my $foo = 123223;
my @data = split //, $foo;
splice_data(\@data);
say "@data";
A few more comments
The question's code happens to work as intended, only the final printing is wrong
No strict and warnings! Always have them at the beggining of programs. They are directly helpful, save you from various kinds of bugs, and generally push to improve all manner of programming practice
In general, better define subs at the top of the program so that they can't accidentally "see" data defined before them (but can only use data specifically passed to them)
Use feature
say
for general printing, or print if there shouldn't be a linefeed (newline). The printf is used only for specific formatting
As evident by many links here I advise reading documentation for everything involved.
CodePudding user response:
Try this out:
use strict; use warnings;
use Data::Dumper;
my $foo = 123223;
my @data = split(//, $foo);
print "Before:\n".Dumper(\@data);
splice_data(\@data);
print "After:\n".Dumper(\@data);
sub splice_data{
splice(@data,3,1,'1');
return @data;
}
Your code is producing the expected output either if you use print(@data);
or print Dumper(\@data);
printf
is used for formatting the output. See here.